为什么在与负数相比较时,sizeof运算符发生这种情况?

参见英文答案 > sizeof() operator in if-statement5个
这里真的发生了什么现在的输出是“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已经被问到,在找不到之前找不到.

解决方法

sizeof返回无符号的size_t,因此-1被转换为非常大的无符号数.使用正确的警告级别在这里有所帮助,与-Wconversion或-Weverything( note this is not for production use)标志警告我们:
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 )

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...