Reputation: 150
I have the following c code:
int foo = 0;
printf("output1: %08x\n", (~0x0) << (~0));
printf("output2: %08x", (~0x0) << (~foo));
which prints out:
output1: ffffffff
output2: 80000000
Why does shifting by the same number produce a different result?
Upvotes: 1
Views: 160
Reputation: 213306
Basically your snippet is an orgy in undefined behavior.
0x0
literals as well as variables of type int
are signed, meaning they can get negative values. ~0
is always a negative value.Therefore anything can happen in this program, including the whole thing crashing and burning. As a rule of thumb, never use signed variables together with bitwise operators.
Upvotes: 3
Reputation: 36391
Some compiler may told you the reason:
warning: shift count is negative [-Wshift-count-negative]
printf("output1: %08x\n", (~0x0) << (~0));
^ ~~~~
ints are signed and complementing them may produce negative values, and shifting by negative amount is undefined.
For example on my machine it produces:
output1: e785ba48
output2: 80000000
Upvotes: 2