By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,227 Members | 1,373 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,227 IT Pros & Developers. It's quick & easy.

Strangeness with shifts

P: n/a
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.


Jul 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
"Glen Able" <re***********************@hoxtmxail.com> writes:
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.
Jul 22 '05 #2

P: n/a
On Sun, 23 Nov 2003 11:38:40 -0000, "Glen Able"
<re***********************@hoxtmxail.com> wrote in comp.lang.c++:
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
Jul 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.