gpt4 book ai didi

c - 按位左移 (<<) 奇怪的行为

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:24 25 4
gpt4 key购买 nike

gcc按位左移 ( << ) 奇怪的行为。这是我的代码:

#include <stdio.h>
#include <string.h>

void foo(int n){
printf("1<<32:%d\n", 1<<32);
printf("1<<(32-n):%d\n", 1<<(32-n));
}

int main(){
foo(0);
}

如果我将 0 作为参数传递,结果可能会有所不同。编译源代码:

$gcc main.c -o demo -lm -pthread -lgmp -lreadline 2>&1
main.c: In function 'foo':
main.c:5:3: warning: left shift count >= width of type [enabled by default]

执行程序:

$demo

1<<32:0
1<<(32-n):1

这个结果是我从 compile online site 得到的

如果我将 0 传递给它,如何使 foo 函数输出 0? (目前它输出 1)

最佳答案

移位等于或大于左操作数提升类型宽度的值是未定义的行为,因此您必须专门测试并避免这种情况。此外,导致溢出的有符号类型的左移也是未定义的行为,因此您还需要避免移动 31:

printf("1<<(32-n):%d\n", (n > 1 && n < 33) ? 1 << (32-n) : 0);

此特定表达式对未定义的情况使用 0,但如果需要,您可以以不同方式处理这些情况。

关于c - 按位左移 (<<) 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16879251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com