Search code examples
cexpressionsizeofoperator-precedenceunary-operator

The result of "sizeof" depends on the location of the brackets. Why?


There is a code:

 float x=-8.92;
 int y=5;
 printf("%u\n", sizeof x+y);
 printf("%u\n", sizeof (x+y));

Conclusion:

9
4

Why is this happening(result 9)? After all, these are simple unary operations.


Solution

  • This expression

    sizeof x+y
    

    is equivalent to the expression

    ( sizeof x ) + y
    

    So as sizeof x is equal to sizeof( float ) that is 4 then the result of the original expression is equal to 9.

    The operator sizeof is an unary operator and its operand is in turn an unary expression. That is the operator in particularly is defined like

    sizeof unary-expression
    

    x + y is an additive expression while the variable x as a primary expression is in turn an unary expression. Thus the operator is applied to the variable x.

    On the other hand, the expression ( x + y ) is a primary expression and due to the usual arithmetic conversions has the type float. So in this case that is when the expression is written like sizeof( x + Y ) the operator sizeof is again applied to a primary (unary) expression and is equivalent to sizeof( float ).

    Pay attention to that instead of the conversion specifier %u you shall use the conversion specifier %zu in the calls of printf. The type of the both expressions sizeof x + y and sizeof( x + y ) is size_t that is an implementation defined type that usually is an alias for the type unsigned long. For the type size_t there is defined the conversion specifier zu that you shall use. Otherwise a call of printf with an incorrect conversion specifier can invoke undefined behavior.