When I do a left shift of a hex I get -1 as output with the following code:
unsigned int i,j=0;
i= (0xffffffff << (32-j));
printf(\"%d\",i);
Shifting a 32-bit variable by 32 yields undefined behavior.
Here is the assembly generated by the VS-2013 compiler:
int n = 0;
mov dword ptr [n],0
int a = 0xFFFFFFFF << 32;
mov dword ptr [a],0
int b = 0xFFFFFFFF << (32-n);
mov ecx,20h
sub ecx,dword ptr [n]
or eax,0FFFFFFFFh
shl eax,cl
mov dword ptr [b],eax
As you can see, what happens de-facto is:
32-n
with n==0
), the compiler uses shl
The actual result of shl
depends on the implementation of this operation in the underlying architecture. On your processor, it probably takes the 2nd operand modulo 32, hence the 1st operand is shifted by 0.
Again, the description above is not dictated by the standard, so it really depends on the compiler in use.
It's undefined behavior to left-shit 32
or greater on a 32-bit integer. That's what the error is about.
C11 6.5.7 Bitwise shift operators
The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. 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.