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

c – 为什么`1 << 32`和`int i = 32; 1 <&l

发布时间:2020-12-16 10:36:35 所属栏目:百科 来源:网络整理
导读:代码如下所示.我在VS,clang和G上测试过它.所有这些都表明1 32和1我(我32岁)是不同的.我看了一下组装.看起来编译器计算1 32在编译.我认为这种不一致应该是一个错误,或者它只是C的另一个未定义的行为. #include iostreamint main(int argc,char *argv[]){ std:
代码如下所示.我在VS,clang和G上测试过它.所有这些都表明1 <<< 32和1<<我(我32岁)是不同的.我看了一下组装.看起来编译器计算1<<<< 32在编译.我认为这种不一致应该是一个错误,或者它只是C的另一个未定义的行为.

#include <iostream>

int main(int argc,char *argv[])
{
    std::cout << (1 << 32) << std::endl;
    int i = 32;
    std::cout << (1 << i) << std::endl;
    return 0;
}

结果:

clang++:
1 << 32:73832
1 << i:1
g++:
1 << 32:73832
1 << i:1

解决方法

C标准说

The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type,the value of the result is E1×2^E2,reduced modulo one more than the maximum value representable in the result type. Otherwise,if E1 has a signed type and non-negative value,and E1×2^E2 is representable in the result type,then that is the resulting value; otherwise,the behavior is undefined.

然后

The type of the result is that of the promoted left operand. The behavior is undefined if the right operand is negative,or greater than or equal to the length in bits of the promoted left operand.

在这种情况下,你不应该期待任何好处.

(编辑:李大同)

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

    推荐文章
      热点阅读