Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does sizeof(int) return in this case?

#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 .

like image 803
Abdul Avatar asked Dec 01 '22 15:12

Abdul


1 Answers

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)

like image 83
Gyapti Jain Avatar answered Dec 09 '22 23:12

Gyapti Jain