Strangeness with shifts

G

Glen Able

The behaviour of << and >> arithmetic operators (under VC++6, x86) seems
rather odd to me.

Shifts at runtime seem to only use the bottom 5 bits of the shift amount (an
x86 issue I suppose), but the compile time evaluation will do as you'd
expect (so i << 32 is 0, rather than i).

Also compile time shifts do some weird clamping where, e.g.
-99 >> 20 is -1
and -99 >> -1 is -1

Does any of this seem acceptable behaviour (particularly the fact that a
simple arithmetic operation can have different results and compile and
runtime) ?


thanks.
 
F

Florian Weimer

Glen Able said:
Does any of this seem acceptable behaviour (particularly the fact that a
simple arithmetic operation can have different results and compile and
runtime) ?

According to the standard, behavior in these cases is undefinded, so
the implementation is correct.
 
J

Jack Klein

The behaviour of << and >> arithmetic operators (under VC++6, x86) seems
rather odd to me.

Shifts at runtime seem to only use the bottom 5 bits of the shift amount (an
x86 issue I suppose), but the compile time evaluation will do as you'd
expect (so i << 32 is 0, rather than i).

Also compile time shifts do some weird clamping where, e.g.
-99 >> 20 is -1
and -99 >> -1 is -1

Does any of this seem acceptable behaviour (particularly the fact that a
simple arithmetic operation can have different results and compile and
runtime) ?


thanks.

From the ISO C++ standard:

=====
[expr.shift] 5.8 Shift operators
1 The shift operators << and >> group left to right.

[snip grammar]

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.
=====

So when you invoke undefined behavior with a right operand of greater
than 31 (for Visual C++), the C++ language no longer knows nor cares
what happens. When you generate undefined behavior, you most
certainly have different results even with "simple arithmetic
operation".

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top