Operator after increment in C

I accidentally coded code when I wrote this 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 run the code, I get the result,

 i : 10 sizeof(i++) is: 4 i : 10 

I was puzzled by this result, since I expected that I ++ inside the sizeof operator would increase i. But it seems not. Therefore, 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, output:

 i : 10 sizeof(i++) is: 4 i : 11 

Now I am more and more puzzled.

Sorry if this is a noob question (as I am), but I really don't understand how Google is for such a problem!

Why is the meaning of me different in these two programs? Please, help!

+4
source share
2 answers

sizeof() not a function of execution. It just gives you the size of the variable or the size of the return value of the function.

So, in the first example, you simply get the size of the result of the post-increment operator for an integer that is an integer ... 4 bytes.

In your example, you simply print the return value of your method, which returns 4, and then the variable increments, and you print 11.

+5
source

sizeof does not evaluate its operand (except for situations like VLA).

This means that sizeof(*(T*)(NULL)) same as sizeof(T) and is absolutely true.

+5
source

Source: https://habr.com/ru/post/1481629/


All Articles