可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This question already has an answer here:
Can You justify the below code:
#include 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 int main() { if((int)sizeof(int) > -1) { printf("\nTrue\n"); } else { printf("\nFALSE\n"); } }