简体   繁体   中英

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 .

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM