Toby
Toby

Reputation: 150

Shifting by a number is different than shifting by a variable

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

Answers (2)

Lundin
Lundin

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.
  • Left-shifting a signed int with negative value invokes undefined behavior. (6.5.7/4)
  • Attempting to shift more positions than there's room in the left operand invokes undefined behavior. (6.5.7/3)
  • Attempting to shift a negative amount of bits invokes undefined behavior. (6.5.7/3)

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

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

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

Related Questions