简体   繁体   中英

How come I get a big int when I bitwise shift 1 << 45

Why do I get such a big int?

int ans = 1 << 45;
printf("Check: %d", ans);
return 0;

Check: 1858443624

This is undefined behavior in C. Anything can happen, including stuff like processor exceptions, or unpredictable changes in other parts of the program (which can happen as a side effect of aggressive compiler optimizations).

6.5.7/3 [...] If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

Source

According to the C standard

An expression is shifted by a negative number or by an amount greater than or equal to the width of the promoted expression (6.5.7).

is undefined behavior, so the compiler is free to do anything for the code you give here.

90? No way. You need to read what bit-shifting does. 1<<45 is essentially 2^45 . Besides, int is only 31 bits (excluding the sign bit), so by trying to shift 45 bits, you're causing undefined behavior.

Quick example:

1 << 0  =  1  = 0x01  = 00000001b
1 << 1  =  2  = 0x02  = 00000010b
1 << 2  =  4  = 0x04  = 00000100b
1 << 3  =  8  = 0x08  = 00001000b

clang (as used in X-Code; AFAIK they don't use gcc anymore) is funny with this:

stieber@gatekeeper:~$ clang Test.c -Wno-shift-count-overflow; ./a.out
Check: -1344872728
stieber@gatekeeper:~$ clang Test.c -Wno-shift-count-overflow; ./a.out
Check: -1066238232
stieber@gatekeeper:~$ clang Test.c -Wno-shift-count-overflow; ./a.out
Check: -1373126936
stieber@gatekeeper:~$ clang Test.c -Wno-shift-count-overflow; ./a.out
Check: 779153128

Apparently, they randomize the result :-)

1) As everybody has already said, the answer is "undefined behavior".

2) In practice, just about every compiler I'm familiar with will give you "0".

3) In practice, most self-respecting compilers will also give you a warning:

x.cpp: In function `int main (int, char **)':
x.cpp:7: warning: left shift count >= width of type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM