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

前端 未结 9 1653
清酒与你
清酒与你 2020-11-22 09:36

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

#include 

int main() {
    int x = 5;
    printf(\"%d and \", sizeof(x++)); // note 1
    print         


        
相关标签:
9条回答
  • 2020-11-22 10:16

    sizeof runs at compile-time, but x++ can only be evaluated at run-time. To solve this, the C++ standard dictates that the operand of sizeof is not evaluated. The C Standard says:

    If the type of the operand [of sizeof] is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

    0 讨论(0)
  • 2020-11-22 10:19

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

    0 讨论(0)
  • 2020-11-22 10:26

    Note

    This answer was merged from a duplicate, which explains the late date.

    Original

    Except for variable length arrays sizeof does not evaluate its arguments. We can see this from the draft C99 standard section 6.5.3.4 The sizeof operator paragraph 2 which says:

    The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

    A comment(now removed) asked whether something like this would evaluate at run-time:

    sizeof( char[x++]  ) ;
    

    and indeed it would, something like this would also work (See them both live):

    sizeof( char[func()]  ) ;
    

    since they are both variable length arrays. Although, I don't see much practical use in either one.

    Note, variable length arrays are covered in the draft C99 standard section 6.7.5.2 Array declarators paragraph 4:

    [...] If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type.

    Update

    In C11 the answer changes for the VLA case, in certain cases it is unspecified whether the size expression is evaluated or not. From section 6.7.6.2 Array declarators which says:

    [...]Where a size expression is part of the operand of a sizeof operator and changing the value of the size expression would not affect the result of the operator, it is unspecified whether or not the size expression is evaluated.

    For example in a case like this (see it live):

    sizeof( int (*)[x++] )
    
    0 讨论(0)
提交回复
热议问题