shift operation in C++

Jan 15, 2009 at 1:59pm
I found something unexpected about shift opeartion in C++ when I was solving my bug, as the following

I tried to shift an unsigned int var:

int ret = 0;
int var = 1
for( int i = 0; i < 60; ++i )
{
ret = var << i;
}

when i < 32, it was allright, ret = 2^i and i = 32, ret = 0;
but it was incredible when i > 32 that ret = 2^((i-1)%32).

How could it be that? I thought ret should be 0 for any i when i>32.

So Could anybody show me how "<<" acts ?
OS: slackware
GCC: 3.3.4
Jan 15, 2009 at 2:19pm
closed account (z05DSL3A)
http://en.wikipedia.org/wiki/Bit_shifting#Bit_shifts may help
Jan 15, 2009 at 2:34pm
I believe the exact behavior of shifts is implementation-defined when the right operand is >= the size in bits of the left operand.
GCC in particular applies a modulo on it, such that for E1<<E2, E2 being >=sizeof(E1)*8, E2%=sizeof(E1)*8. Therefore, x<<32==x<<0, x<<33==x<<1, and so on. This can be verified because 0x8000000<<1!=1.
Jan 15, 2009 at 3:14pm
closed account (z05DSL3A)
5.8 Shift operators [expr.shift]

1 The shift operators << and >> group left-to-right.

shift-expression: additive-expression
shift-expression << additive-expression
shift-expression >> additive-expression


The operands shall be of integral or 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.

2 The value of E1 << E2 is E1 (interpreted as a bit pattern) left-shifted E2 bit positions; vacated bits are
zero-filled. If E1 has an unsigned type, the value of the result is E1 multiplied by the quantity 2 raised to
the power E2, reduced modulo ULONG_MAX+1 if E1 has type unsigned long, UINT_MAX+1 otherwise.
[Note: the constants ULONG_MAX and UINT_MAX are defined in the header <climits>). ]

3 The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a
signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 divided
by the quantity 2 raised to the power E2. If E1 has a signed type and a negative value, the resulting value
is implementation-defined.
ISO/IEC 14882-2003
Last edited on Jan 15, 2009 at 3:20pm
Jan 16, 2009 at 2:13am
As Grey Wolf referenced, when overflowed, the behavior is undefined. However, it behaves as helios said.
My cowokers told me that there would be a modulo on the right opeand by CPU when it overflowed, but none of us found the definition of such operation of CPU...
Topic archived. No new replies allowed.