Why does sizeof(x++) not increment x?

2018-12-31 10:16发布

Here is the code compiled in dev c++ windows:

#include <stdio.h>

int main() {
    int x = 5;
    printf("%d and ", sizeof(x++)); // note 1
    printf("%d\n", x); // note 2
    return 0;
}

I expect x to be 6 after executing note 1. However, the output is:

4 and 5

Can anyone explain why x does not increment after note 1?

标签: c sizeof
9条回答
倾城一夜雪
2楼-- · 2018-12-31 11:00

sizeof is a compile-time builtin operator and is not a function. This becomes very clear in the cases you can use it without the parenthesis:

(sizeof x)  //this also works
查看更多
残风、尘缘若梦
3楼-- · 2018-12-31 11:10

sizeof() operator gives size of the data-type only, it does not evaluate inner elements.

查看更多
笑指拈花
4楼-- · 2018-12-31 11:11

sizeof is a compile-time operator, so at the time of compilation sizeof and its operand get replaced by the result value. The operand is not evaluated (except when it is a variable length array) at all; only the type of the result matters.

short func(short x) {  // this function never gets called !!
   printf("%d", x);    // this print never happens
   return x;
}

int main() {
   printf("%d", sizeof(func(3))); // all that matters to sizeof is the 
                                  // return type of the function.
   return 0;
}

Output:

2

as short occupies 2 bytes on my machine.

Changing the return type of the function to double:

double func(short x) {
// rest all same

will give 8 as output.

查看更多
登录 后发表回答