0

In the following code

#include <stdio.h>

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

I get the output as "False" rather than "True".My understanding is that sizeof operator just returns the size of int which will be 4 in this case.

Why is the condition evaluated as false?

The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75
Ross
  • 617
  • 2
  • 9
  • 23

3 Answers3

10

sizeof generates a size_t which is always positive. You are comparing it with -1 which is probably promoted in size_t which gave you a HUGE number, most likely greater than the size of an int.

To make sure of it, try this:

printf("%zu\n", sizeof(int));
printf("%zu\n", (size_t)(-1));

[EDIT]: Following comments (some have been removed), I precise indeed that sizeof is an operator, not a function.

n0p
  • 3,399
  • 2
  • 29
  • 50
2

From the standard, C11, 6.5.3.4 The sizeof and _Alignof operators:

5 The value of the result of both operators is implementation-defined, and its type (an unsigned integer type) is size_t, defined in (and other headers).

So, the sizeof operator yields an unsigned value. You then compare an unsigned value with a signed value. That is dealt with by converting the signed value to be unsigned, which explains the behaviour that you see.

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

First, running your code:

cc1plus: warnings being treated as errors
In function 'int main()':
Line 3: warning: comparison between signed and unsigned integer expressions

Then fixing it:

int main()
{
   if ((int)sizeof(int) > -1) // cast value of sizeof(int) to int before compare to int
       printf("True");
   else
       printf("False");
   return 0;
}

Result:

True
Martin G
  • 17,357
  • 9
  • 82
  • 98