加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:13:58 所属栏目:百科 来源:网络整理
导读:参见英文答案 sizeof() operator in if-statement5个 这里真的发生了什么现在的输出是“False”: #include stdio.hint main(){ if (sizeof(int) any_negative_integer) printf("True"); else printf("False"); return 0;} 如果我把它改成: if (sizeof(int)
参见英文答案 > 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 )

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读