1

Can You justify the below code:

#include<stdio.h>
int main()
{
    if(sizeof(int) > -1)
    {
            printf("\nTrue\n");
    }
    else
    {
            printf("\nFALSE\n");
    }
}

The output is FALSE .....suggest me the reason

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Bhargav
  • 21
  • 5
  • 4
    gcc even has a warning for this `foo.c:4:20: warning: comparison between signed and unsigned integer expressions [-Wsign-compare] if(sizeof(int) > -1)` - you can easily enable verbose warnings in gcc with `-Wall -Wextra` which is something everyone should be doing. – Andreas Grapentin Dec 08 '15 at 08:47
  • [Why is −1 > sizeof(int)?](http://stackoverflow.com/q/3100365/995714) – phuclv Nov 11 '16 at 07:03

3 Answers3

7

sizeof(int) has type size_t, which is an unsigned integer type.

-1 has type int, which is a signed integer type.

When comparing a signed integer with an unsigned integer, first the signed integer is converted to unsigned, then the comparison is performed with two unsigned integers.

sizeof(int) > (unsigned int)-1 is false, because (unsigned int)-1 is a very large number on most implementations (equal to UINT_MAX, or the largest number which fits in an unsigned int).

user253751
  • 57,427
  • 7
  • 48
  • 90
  • 4
    *When comparing a signed integer with an unsigned integer, first the signed integer is converted to unsigned* This is true only if the conversion rank of the unsigned integer type is greater or equal than the one of the signed integer type. – ouah Dec 08 '15 at 08:55
2
sizeof

yields a value of an unsigned type (namely size_t).

In sizeof(int) > -1 expression, the usual arithmetic conversion applies and -1 is converted to the unsigned type of sizeof which results in a huge unsigned value greater than -1.

ouah
  • 142,963
  • 15
  • 272
  • 331
2

It's because the sizeof operator returns an unsigned integer type. When compared with a signed integer type, the signed integer is converted to unsigned. So in effect, you were comparing sizeof(int) against the largest possible unsigned integer.

You can force the size to signed by casting:

#include <stdio.h>

int main()
{
    if((int)sizeof(int) > -1)
    {
            printf("\nTrue\n");
    }
    else
    {
            printf("\nFALSE\n");
    }
}
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
  • To be picky, the signed integer is _converted_ to unsigned. It is done implicitly in this case, as opposed to casting which is always something done explicitly by the programmer. – Lundin Dec 08 '15 at 10:09
  • @Lundin Ok, I changed it to use the term "converted". – Tom Karzes Dec 08 '15 at 10:26