32-bit integer offset by 32 bits

I am building some C code and I need the bitrate of 32 bit int left 32 bit. When I run this code with parameter n = 0, the shift does not occur.

int x = 0xFFFFFFFF; int y = x << (32 - n); 

Why is this not working?

+4
source share
2 answers

Move your own danger. By standard, you want to make undefined behavior .

C99 Β§6.5.7

3 . Integer promotions are executed on each of the operands. The result type is the advanced left operand. If the value of the correct operand is negative or greater than or equal to the width of the advanced left operand, the behavior is undefined.

In other words, if you try to shift a 32-bit value to something greater than 31 bits or a negative number, you will get undefined.

+9
source

According to section 3.3.7 Bitwise shift operators in the draft standard C89 (?) :

If the value of the correct operand is negative or greater than or equal to the bit width of the advanced left operand, the behavior is undefined.

Assuming int is 32-bit on a system in which you compile code when n is 0, you swap 32 bits. According to the above statement, your code leads to undefined behavior .

+3
source

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


All Articles