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.
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.
The sizeof operator has higher precedence than the binary addition operator +. So this:
sizeof x+y
Parses as:
(sizeof x)+y
So in the first expression you're getting the size of a float which is 4 on your system and adding the value 5 to that, resulting in 9. For the second expression, the subexpression x+y has type float because of the usual arithmetic conversions, so the result is 4 which is what's printed.
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.
sizeof x+y is the same as (sizeof x) + y, i.e. sizeof has higher precedence than +.
Your compiler should have warned you about the mismatch between the printf() format string (%u) and the argument (size_t, int or other) - if you're using GCC, you should add -Wall -Wextra to your compilation command.
The result of “sizeof” depends on the location of the brackets. Why?
Because "brackets" override operator precedences.