Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

sizeof

I don't know why the sizeof operator is not evaluated in a for loop condition at run time. I am trying this simple code with different C compilers but it always print nothing. But if I replace sizeof(i) with 4 then it works fine:

for(int i = -2; i <= 4; i++)

#include <stdio.h>

int main()
{

    for(int i = -2; i <= sizeof(i); i++)
        printf("Hello World");

    return 0;
}
like image 252
voidpointer Avatar asked Jun 13 '20 06:06

voidpointer


People also ask

Why sizeof is an operator not a function?

sizeof operator is compile time entity not runtime and don't need parenthesis like a function. When code is compiled then it replace the value with the size of that variable at compile time but in function after function gets execute then we will know the returning value.

Does sizeof evaluate?

When the sizeof() method is passed a fixed size structure: In this case, the sizeof() operator does not evaluate the parameter. Only the type of the parameter is checked and its size is returned.

Is sizeof evaluated at compile-time?

sizeof is evaluated at compile time, but if the executable is moved to a machine where the compile time and runtime values would be different, the executable will not be valid.

Is sizeof () a function?

The sizeof() function in C is a built-in function that is used to calculate the size (in bytes)that a data type occupies in ​the computer's memory. A computer's memory is a collection of byte-addressable chunks.


2 Answers

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.

like image 59
Sourav Ghosh Avatar answered Sep 21 '22 05:09

Sourav Ghosh


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

like image 40
pmg Avatar answered Sep 20 '22 05:09

pmg