这段代码的“假”输出背后的原因是什么?
此 C 代码给出输出“False”并且else块正在执行。
的值为sizeof(int)4,但 的值为sizeof(int) > -10。
我不明白发生了什么。
#include <stdio.h>
void main()
{
if (sizeof(int) > -1 )
{
printf("True");
}
else
{
printf("False");
}
printf("n%d", (sizeof(int)) ); //output: 4
printf("n%d", (sizeof(int) > -1) ); //output: 0
}
回答
您的sizeof(int) > -1测试是比较两个无符号整数。这是因为sizeof操作者返回一个size_t值,该值是的unsigned类型,所以-1值被转换为它的“等效”表示为无符号值,它实际上是在最大可能为一个值unsigned int。
要解决此问题,您需要将值显式sizeof转换为 (signed) int:
if ((int)sizeof(int) > -1) {
printf("True");
}
- Because the rules say so: https://stackoverflow.com/questions/5416414/signed-unsigned-comparisons
-
@abelenky Indeed (although that post is for C++). From [this C11 Draft Standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) (6.3.1.8): *Otherwise, if the operand that has unsigned integer type has rank greater or
equal to the rank of the type of the other operand, then the operand with
signed integer type is converted to the type of the operand with unsigned
integer type.* - −1 is converted by value, not representation, to 2^N−1, where N is the number of bits in `size_t`. For example, −1 has different representations in two’s complement (111…111), one’s complement (111…110), and sign-and-magnitude (100…001), but `(size_t) -1` is always 2^N−1 per the C standard. Also note that `size_t` can be narrower than `int`, in which case it is promoted and the `-1` is not, and `sizeof(int) > -1` evaluates to true.