0
int main()
{
     if (sizeof(int) > -1 )
           printf("True");
     else
           printf("False");
     return 0 ;
}

I expected the program results in "True" but after executing it results in "False". Could anyone explain why this is the case?

Jonas Schäfer
  • 20,140
  • 5
  • 55
  • 69
Muniyasamy V
  • 81
  • 1
  • 4
  • 9
  • 2
    What did you find out the `sizeof` **operator** yields? Which type? And format this mess properly. Read [ask]. A modern compiler should warn about this comparison. If not, enable all recommended warnings (at least `-Wall -Wextra -Wconversion`). And alway fix the cause for warnings before asking. – too honest for this site May 21 '17 at 13:49
  • 2
    In C, the sizeof operator inside the if statement works exactly as it works outside the if statement. – Mike Nakis May 21 '17 at 13:59

1 Answers1

3

sizeof returns size_t, which is unsigned.

Comparison unsigned and signed numbers needs an attention in C, because of such comparison usually gives surprising results for beginner programmers, as we can see here.

Basically, -1 gets converted to a very big unsigned int, so your condition is false.

Andriy Berestovskyy
  • 8,059
  • 3
  • 17
  • 33