Why is the sizeof operator not evaluated in a for loop condition?

The problem is , the result of sizeof() operator is of type size_t, which is an unsigned type.

Next, in the comparison, i <= sizeof(i) as per the usual arithmetic conversion rules, -2, which is a signed value, gets promoted to an unsigned value, producing a huge value, evaluating the condition to false. So the loop condition is not satisfied and the loop body is not executed.

Run your program through a debugger and see the values in each step, it'll be more clear to you once you see the promoted values in the comparison.


sizeof yields a value of unsigned type variety (size_t). The i is converted to that type and the comparison executed as

(size_t)-2 <= 4

something like 4000000000 < 4


you need to typecast sizeof(i) into int. that should solve the problem.

so just replace for(int i = -2; i <= sizeof(i); i++) with for(int i = -2; i <= (int) sizeof(i); i++)

Tags:

C

Sizeof