6
#include <stdio.h>
main()
{
   if (sizeof(int) > -1)
       printf("True");
   else
       printf("False");
}

ANSWER:

False

but according to the logic sizeof(int) return 2 and if(2>-1) return 1 and it should print True.

Why it is behaving otherwise?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Harish
  • 425
  • 7
  • 22

3 Answers3

14

First of all, the value produced by sizeof is of size_t which is unsigned type. NOTE

As the unsigned type is of higher rank than the signed type, while performing the comparison, as per the norms of the relation operator, the usual arithmetic conversions are performed, meaning the signed type is promoted to unsigned type.

In your case, the -1, when considered as unsigned, represent the highest possible unsigned value, thus, no wonder

 if (sizeof(int) > -1)

Evaluates to false.

Moral of the story: Attempted comparison between a signed and an unsigned is expected to produce weird result, just as in your case. You should enable compiler warning and try to solve the issues reported by the compiler.


NOTE:

From C11, chapter §7.19, <stddef.h>,

size_t
which is the unsigned integer type of the result of the sizeof operator.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

sizeof is an operator which returns the size and the returned value type is unsigned int. Since unsigned is having higher rank than singed type, -1 is treated as unsigned number. -1 in this case is treated as 0xFFFF. Hence if (sizeof(int) > 0XFFFF) is evaluated to false.

enter image description here

NJMR
  • 1,886
  • 1
  • 27
  • 46
1

If you write

if ( ( int )sizeof(int) > -1)

you will get the expected result that is True.

Operator sizeof returns a value of type size_t that corresponds to some implementation defined unsigned integer type.

From the C STandard (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).

The rank of size_t in any case greater than or at least equal to the rank of type int. It means that when the compiler need to determine the type of an expression it converts operand will lower rank to the type of the operand with higher rank. If operands have the same rank but one operand has unsigned integer type and other has signed integer type then the common type is unsigned int type.

Thus in the condition of the if statement

if ( sizeof(int) > -1)

-1 is converted to unsigned integer type size_t and due to its internal representation where all bits are set to 1 is freater than the value of sizeof( int )

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Actually, because of the way the standard specifies conversions from signed to unsigned, the internal representation of a negative number doesn't really matter... `-1` converts to the same unsigned value regardless (maximum value for the unsigned type). – Dmitri Aug 12 '15 at 07:02