Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifting 64 bit value left by 64 bits in C++ giving weird results [duplicate]

Possible Duplicate:
64bit shift problem

I'm using Visual Studio 2012 on Windows 8 64-bit, targeting x64 in debug mode, using an AMD Phenom II.
So Basically...

uint64_t Foo = 0xFFFFFFFFFFFFFFFF << 64;//Foo is now 0x0000000000000000
uint64_t Derp = 64;
uint64_t Bar = 0xFFFFFFFFFFFFFFFF << Derp;//Foo is now 0xFFFFFFFFFFFFFFFF

Using a lower value such as 63 restores normal behavior.
Why is this happening and how can I get around it?

Update: I switched to release mode. Lo and behold, the issue vanished and both returned 0. But the issue remains in debug mode which is where I need to be in order to debug my code.

like image 647
retep998 Avatar asked Aug 05 '12 14:08

retep998


1 Answers

Shift operation has undefined behavior if you shift by values greater than or equal to the bit width.

From Section 5.8 p1 in the C++11 draft:

The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand. The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

like image 97
jxh Avatar answered Sep 28 '22 14:09

jxh