void main() { if(sizeof(int) > -1) printf(“true”); else printf(“false”); ; [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:08:02

问题:

This question already has an answer here:

void main() {     if(sizeof(int) > -1)         printf("true");     else         printf("false");     } 

I expected the output to be true but it is false. Can anybody please explain me the reason for the output.

回答1:

sizeof(int) is of type size_t, which is an unsigned integer type. So in the expression if(sizeof(int) > -1), -1 is converted to an unsigned integer, which is very big.

BTW, use int main instead of the non-standard void main.



回答2:

sizeof(int) returns size_t which is as unsigned int.

Usual arithmetic conversions are implicitly performed for common type.

int --> unsigned int --> long --> unsigned long --> long long --> unsigned long long --> float --> double --> long double 

int value(-1) is converted to unsigned int as part of implicit conversion.

-1 will be represented as 0xFFFF in 16 bit machine(for example).

So expression becomes,

if(sizeof(int) > -1 ) ==> if(2 > 0xFFFF) 

And false is printed. I suggest to try if((int)sizeof(int) > -1 ) for proper result.



回答3:

The data type of value provided by sizeof is size_t which is (in most machines) an unsigned int/long, therefore, when you compare it with -1, -1 is type promoted to unsigned which then becomes 0xFFF.. , which is the largest value that datatype can hold, therefore your comparison fails.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!