haimg haimg - 1 year ago 72
C Question

Cannot understand shift operator behavior in C code

Look at this sample C code (extracted a test case as an example):

main() {
unsigned long a, b;
int c;
c = 32;
a = 0xffffffff << 32;
b = 0xffffffff << c;
printf ("a=%x, b=%x\n", a, b);

a=0, b=ffffffff

I cannot understand why b is not zero, just like a. I tested this on Microsoft C and GCC.

Update: I fixed the stupid typo (should have been << c and not << b of course). But my question still stands, e.g. the result is still the same.

Answer Source

In C it is undefined behavior to left shift more than the width of the promoted operand.

(C99, 6.5.7p3) "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."

I assume in the examples below int and unsigned int types are 32-bit.

The type of an unsuffixed hexadecimal integer constant is the first in the corresponding list in which its value can be represented: int, unsigned int, long, unsigned long, long long, unsigned long long.

So here 0xFFFFFFFF is of type unsigned int and 0xFFFFFFFF << 32 is undefined behavior.