Bit shift in C

I have C code that bothers me:

int a = 1;
int b = 32;
printf("%d\n %d\n", a<<b, 1<<32);

Output signal

1
0

The code was running on Ubuntu 16.04 (Xenial Xerus), and I compiled it using gcc -m32 a.cGCC version 5.4.0.

I read several posts that explained why a<<b1 outputs, but I don’t understand why the results 1<<32are 0. I mean, what is the difference between a<<band 1<<32?

+4
source share
4 answers

The offset of the 32-bit intremaining to 32 is undefined, so any value can be obtained as a result. Your C compiler should warn you about this in case of an expression 1<<32.

, , , :

  • a << b ,
  • 1<<32 - ,

, 32, 32 . 32, . , undefined. , - .

+6

a<<b 1<<32 - undefined , .

C11 §6.5.7

3:

. - . : undefined, .

4:

E1 << E2 E1 E2 ; . E1 , E1 × 2E2, , . E1 E1 × 2E2 , ; undefined.

, , , undefined.

GCC:

warning: left shift count >= width of type [-Wshift-count-overflow]
     printf("%d\n%d",a<<b,1<<32);
+3

.

int 32 , 1 < 31 - = -2147483648. -1 < 31 .

>= , undefined.

0

A shift in a constant value compared to a shift in bits b can lead to behavior in accordance with the rule that undefined behavior can be optimized from existence. In other words, a constant offset is probably optimized differently than a variable bit offset. Both are obviously undefined behavior, so the compiler can handle any case in any way. It can literally generate random numbers.

0
source

Source: https://habr.com/ru/post/1687548/


All Articles