1

Running the following code:

unsigned int right_shift_val = (0x20);
printf("right shift 0xFC0 [by 0x%x], method #1: 0x%x \n", right_shift_val, 0xFC0 >> right_shift_val);
printf("right shift 0xFC0 [by 0x20], method #2: 0x%x \n",  0xFC0 >> 0x20);

Yields the results:

right shift 0xFC0 [by 0x20], method #1: 0xfc0                                                                                                                                      
right shift 0xFC0 [by 0x20], method #2: 0x0 

OnlineGDB url

Why are those two similar operations yield different results?

izac89
  • 3,790
  • 7
  • 30
  • 46
  • Add `-Wall -Wextra` to the command line arguments and gcc will tell you. – Shawn Dec 15 '20 at 08:25
  • What result do you expect by shifting a 32-bit value by 32 bits? It's undefined. In the first case a run-time shift of `32 % 32` bits leaves no change. In the second case the compiler figured out the result of the hard-coded values should be `0`. – Weather Vane Dec 15 '20 at 08:33
  • It's UB. C17 6.5.7 "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." – Lundin Dec 15 '20 at 08:59
  • The first is done at runtime, the second is optimized away by the compiler – Shlomi Agiv Dec 15 '20 at 09:02

0 Answers0