4

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!

user2290802
  • 253
  • 2
  • 7

2 Answers2

5

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.

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
  • 1
    I'm not concerned of what sizeof() returns. I'm concerned of the final prinf(). After post-increment, I expect x to have a value of 11. But with the example with sizeof() it still has 10 as the final value. But when I replaced sizeof() with another function, the final value of x is 11. That is my concern. – user2290802 May 19 '13 at 13:15
  • 1
    Still answers your question. `sizeof(i++)` is replaced with `4` by the preprocessor/compiler, so `i++` never ends up as machine code in the executable. – user123 May 19 '13 at 13:16
  • 1
    @user2290802 That's what i said, sizeof() is not a runtime function. At compile time it just sees the size of the parameter and inserts that number in its place (sort of). At runtime the i++ doesn't even exist, so it doesn't evaluate. – Yochai Timmer May 19 '13 at 13:18
5

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084