C language if statement with sizeof

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

ANSWER:

False

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

Why does he behave differently?

+6
source share
3 answers

First of all, the value created by sizeof is size_t , type unsigned . Note

Since the unsigned type has a higher rank than the signed type, when performing the comparison, in accordance with the norms of the relation operator, the usual arithmetic conversions are performed, which means that the signed type is advanced to the unsigned type.

In your case, -1 , if it is considered unsigned , is the maximum possible unsigned value, so it’s not surprising

  if (sizeof(int) > -1) 

Returns false.

Moral of the story: An attempt to compare between signed and unsigned is expected to produce a strange result, as in your case. You must enable the compiler warning and try to solve the problems that the compiler reports.


Note:

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

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

+14
source

sizeof is an operator that returns the size, and the type of the return value is unsigned int . Since unsigned has a higher rank than the singed type, -1 is considered an unsigned number. -1 in this case is considered as 0xFFFF. Therefore, if (sizeof(int) > 0XFFFF) evaluates to false .

enter image description here

+2
source

If you write

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

You will get the expected result True .

The sizeof operator returns a value of type size_t that corresponds to a specific integer type defined by the implementation.

From C STandard (6.5.3.4 sizeof and alignof operators)

5 The value of the result of both operators is determined by the implementation, and its type (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 . This means that when the compiler needs to determine the type of expression that it converts, the operand will lower the rank to the type of the operand with a higher rank. If the operands have the same rank, but one operand has an unsigned integer type and the other has an integer type, then the generic type is of type unsigned int.

Thus, in the condition of the if statement

 if ( sizeof(int) > -1) 

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

+1
source

All Articles