4
#include<stdio.h>
#include<conio.h>

void main()
{   
    if(sizeof(int)>=-2)    
        printf("True");
    else
        printf("False");
}

When I am trying to compile this piece of code using Turbo C++ it is returning False instead of True . But when I tried to print the value of int the program is returning 2.

How can this be possible ? while sizeof(int) is returning 2 and yes 2>=-2 .

Mansuro
  • 4,558
  • 4
  • 36
  • 76
Abdul
  • 69
  • 3

2 Answers2

16

sizeof(int) is replaced with type std::size_t which is unsigned on most of the implementations.

Comparing signed with unsigned leads strange result because of signed being promoted to unsigned.

You can get sensible result as shown below

if(static_cast<int>(sizeof(int)) >= -2)

If you are working on a C compiler

if((int)sizeof(int) >= -2)

Compiling your code with some warning flags -Wall for example should most possibly warn about signed/unsigned comparison. (If you are not ignoring the warnings)

Gyapti Jain
  • 4,056
  • 20
  • 40
2

The type of sizeof is size_t (typedef unsigned int size_t). unsigned int compared with an signed may cause wrong answer.

Chnossos
  • 9,971
  • 4
  • 28
  • 40
wangsquirrel
  • 135
  • 2
  • 12
  • 1
    Not necessarily `unsigned int`. `unsigned long` and `unsigned long long` are probably just as frequent, if not more. The only requirement is that it be an unsigned integral type. – James Kanze Oct 28 '14 at 14:16
  • Can you please re-write the code for me so that it returns true. Thanks in advance. – Abdul Oct 28 '14 at 14:33
  • on 64-bit systems it's most probably `unsigned long` or `unsigned long long` – phuclv Dec 18 '14 at 08:29