按位左移(<<)奇怪的行为 [英] Bitwise Leftshift (<<) strange behavior
问题描述
gcc
按位左移(<<
)奇怪的行为.这是我的代码:
gcc
bitwise Leftshift (<<
) strange behavior. Here is my code:
#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用作参数,则结果可能会有所不同.编译源代码:
If I pass 0 as parameter, the result could be different. Compiling the source code:
$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
此结果是我从编译在线网站
如果将0传递给foo函数,如何使它输出为0? (当前改为输出1)
How can I make the foo function output 0 if I pass 0 to it? (currently it outputs 1 instead)
推荐答案
以等于或大于左操作数提升类型的宽度的值移动是不确定的行为,因此您必须专门测试并避免这种情况.此外,导致溢出的带符号类型的左移也是未定义的行为,因此,您还需要避免31的移位:
Shifting by a value that is equal or greater than the width of the promoted type of the left operand is undefined behaviour, so you must specifically test for and avoid this. In addition, a left-shift of a signed type that results in overflow is also undefined behaviour, so you need to also avoid a shift of 31, too:
printf("1<<(32-n):%d\n", (n > 1 && n < 33) ? 1 << (32-n) : 0);
对于未定义的情况,此特定表达式使用0,但是如果需要,可以按不同的方式处理.
This particular expression uses 0 for the cases that are otherwise undefined, but you can handle those differently if you need to.
这篇关于按位左移(<<)奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!