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

4

8

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;
}
Omnipotence answered 13/6, 2020 at 6:16 Comment(0)
W
9

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.

Walkthrough answered 13/6, 2020 at 6:22 Comment(1)
This is true if the rank of size_t is greater than or equal to the rank of int, otherwise the code will work as both values will be converted into int. It's the "usual arithmetic conversions" rather than the "arithmetic promotion rules" which may be confused for "integer promotions".Eggshell
A
4

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

Advisedly answered 13/6, 2020 at 6:22 Comment(0)
O
2

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++)

Oozy answered 13/6, 2020 at 6:22 Comment(0)
K
0

sizeof() returns size_t which is an unsigned type. You can try this code instead:

#include<stdio.h>
int main()
{
  int i=-2,j;
  j=(int)sizeof(i);
  for(i=-2;i<=j;i++)
     printf("HELLO\n");
  return 0;
}

You can typecast sizeof() to int.

Kreis answered 13/6, 2020 at 6:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.