Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post-increment operator in C

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!

like image 508
user2290802 Avatar asked Dec 26 '22 03:12

user2290802


2 Answers

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.

like image 105
Yochai Timmer Avatar answered Dec 31 '22 01:12

Yochai Timmer


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.

like image 45
Kerrek SB Avatar answered Dec 31 '22 00:12

Kerrek SB