Why is (sizeof(int) > -1) false? [duplicate]

别来无恙 提交于 2019-12-17 10:06:12

问题


Can You justify the below code:

#include<stdio.h>
int main()
{
    if(sizeof(int) > -1)
    {
            printf("\nTrue\n");
    }
    else
    {
            printf("\nFALSE\n");
    }
}

The output is FALSE .....suggest me the reason


回答1:


sizeof(int) has type size_t, which is an unsigned integer type.

-1 has type int, which is a signed integer type.

When comparing a signed integer with an unsigned integer, first the signed integer is converted to unsigned, then the comparison is performed with two unsigned integers.

sizeof(int) > (unsigned int)-1 is false, because (unsigned int)-1 is a very large number on most implementations (equal to UINT_MAX, or the largest number which fits in an unsigned int).




回答2:


sizeof

yields a value of an unsigned type (namely size_t).

In sizeof(int) > -1 expression, the usual arithmetic conversion applies and -1 is converted to the unsigned type of sizeof which results in a huge unsigned value greater than -1.




回答3:


It's because the sizeof operator returns an unsigned integer type. When compared with a signed integer type, the signed integer is converted to unsigned. So in effect, you were comparing sizeof(int) against the largest possible unsigned integer.

You can force the size to signed by casting:

#include <stdio.h>

int main()
{
    if((int)sizeof(int) > -1)
    {
            printf("\nTrue\n");
    }
    else
    {
            printf("\nFALSE\n");
    }
}


来源:https://stackoverflow.com/questions/34151309/why-is-sizeofint-1-false

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