The Peculiar Behavior of sizeof
sizeof is the only keyword in C/C++ which can be used as an operator. sizeof is used to find out the storage space required by a particular variable or constant. But there is a behavioral abnormality shown by the sizeof operator. Consider the program given below.
#include<stdio.h>
int main()
{
int a,b;
a=10;
b=sizeof(++a);
printf("a is %d",a);
printf("\nb is %d\n",b);
return 0;
}
Download
int main()
{
int a,b;
a=10;
b=sizeof(++a);
printf("a is %d",a);
printf("\nb is %d\n",b);
return 0;
}
Download
The expected output is "a is 11" and "b is 4". But the actual output is "a is 10" and "b is 4". Reason? sizeof is an operator and inside which no expression is evaluated. If you are using Turbo C++ by Borland, the output will be "a is 10" and "b is 2" because the size of integer is 2.
The Figure Below Shows the Output
To clarify the doubts, consider the following program.
#include<stdio.h>
int main()
{
int a,b,c,d;
c=1000;
a=10;
b=20;
d=sizeof(c=a+b);
printf("c is %d",c);
printf("\nd is %d\n",d);
return 0;
}
int main()
{
int a,b,c,d;
c=1000;
a=10;
b=20;
d=sizeof(c=a+b);
printf("c is %d",c);
printf("\nd is %d\n",d);
return 0;
}
Here also the expression inside the sizeof operator is not evaluated and the output is "c is 1000" and "d is 4". If the compiler used is Turbo C++ by Borland, then the output will be "c is 1000" and "d is 4" since the size of integer is 2 bytes.
The Figure Given Below Shows the Output
No comments:
Post a Comment