James Kanze
9/25/2008 8:48:00 PM
On Sep 25, 7:44 pm, Juha Nieminen <nos...@thanks.invalid> wrote:
> Richard Herring wrote:
> >> 1 is an int, so when you shift it left by more than 32 you wrap around.
> > Worse. When you shift it left by 32 or more, you get UB.
> > (assuming 'int' is 32 bits on this machine.)
> > 5.8/1:
> > "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."
> That's actually something which should be taken seriously. I
> remember back when I was developing on some UltraSparc
> architecture that if you shifted an integer by more bits than
> there was in the integer, the result would be, IIRC, the
> original value of that integer (rather than zero, like AFAIK
> happens with intel CPUs). In other words, if the amount of
> shift was invalid, the UltraSparc would simply not execute it
> (leaving the original value of the integer intact). This can
> come as a surprise to many.
I think that on a lot of architectures, i << n will actually
execute as i << (n % B), where B is the number of bits in i. So
that on a 32 bit machine, i << 32 shifts 0, i << 33 shifts 1,
etc.
Of course, if the shift count is a constant, the compiler should
warn.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34