这里真的发生了什么现在的输出是“False”:
#include <stdio.h> int main() { if (sizeof(int) > any_negative_integer) printf("True"); else printf("False"); return 0; }
如果我把它改成:
if (sizeof(int) < any_negative_integer)
输出为“True”.
更新:same question已经被问到,在找不到之前找不到.
解决方法
warning: implicit conversion changes signedness: 'int' to 'unsigned long' [-Wsign-conversion] if (sizeof(int) > -1) ~ ^~
对于gcc,您将使用-Wextra标志收到类似的警告:
warning: comparison between signed and unsigned integer expressions [-Wsign-compare] if (sizeof(int) > -1) ^
作为参考,我们知道size_t是从draft C99 standard部分无符号7.17常见的定义,说:
size_t
which is the unsigned integer type of the result of the sizeof operator;[…]
注意,它没有指定任何关于类型的东西,在我的具体情况下,它恰好是unsigned long,但不一定是.
-1的转换是由于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.Otherwise,if the type of the operand with signed integer type can represent
all of the values of the type of the operand with unsigned integer type,then
the operand with unsigned integer type is converted to the type of the
operand with signed integer type.Otherwise,both operands are converted to the unsigned integer type
corresponding to the type of the operand with signed integer type.
所以唯一的时间-1将不会转换为无符号的值将是,如果int可以表示size_t的所有值,这不是这里的情况.
为什么-1最终成为一个大的无符号值,实际上它最终被作为无符号类型的最大值是由于第6.3.1.3节有符号和无符号整数说:
Otherwise,if the new type is unsigned,the value is converted by repeatedly adding or
subtracting one more than the maximum value that can be represented in the new type
until the value is in the range of the new type.49)
所以我们最终得到:
-1 + (UMAX + 1)
这是:
UMAX
因此最终得到:
if (sizeof(int) > UMAX )