I was casually coding when I wrote this C code:
#include <stdio.h>
int main()
{
int i;
i = 10;
printf("i : %d\n",i);
printf("sizeof(i++) is: %d\n",sizeof(i++));
printf("i : %d\n",i);
return 0;
}
And when I ran the code, the result I get is,
i : 10
sizeof(i++) is: 4
i : 10
I was baffled by this result as I expected i++ inside sizeof operator to have incremented i. But it seems not. So out of curiosity I wrote the following program:
#include <stdio.h>
int add(int i)
{
int a = i + 2;
return 4;
}
int main()
{
int i;
i = 10;
printf("i : %d\n",i);
printf("sizeof(i++) is: %d\n",add(i++));
printf("i : %d\n",i);
return 0;
}
for this program, the output is:
i : 10
sizeof(i++) is: 4
i : 11
Now I'm more and more baffled.
Sorry if this is a noob question (which I am) but I don't really understand even how to google for such a problem!
Why is the value of i different in these two programs? Please help!
sizeof()
isn't a runtime function. It just gives you the size of the variable or the size of the return value of a function.
So in the first example, you're just getting the size of the result value of a post-increment operator on an integer which is an integer... 4 bytes.
In your example you're just printing the return value of your method which returns 4, and then the variable increments, and you print 11.
sizeof
does not evaluate its operand (except in VLA-type situations).
That means that sizeof(*(T*)(NULL))
is the same as sizeof(T)
, and perfectly validly so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With