ri************@gmail.com wrote:
K&R states that the right operand must be non-negative.
"The shift operators << and >> perform left and right shifts of their
left operand by the number of bit positions given by the right operand,
which must be non-negative"
unsigned int n = 10;
n <<= -2;
MSVC7 accepts this above code as valid and compiles it.
Should this be allowed, it seems like it could lead to subtle bugs?
The behavior of the shift is undefined, meaning that
the C Standard makes no guarantees about what might happen
if the program attempts to evaluate the offending expression.
"Anything can happen" includes as a special case right-shifting
`n' by two bit positions -- but it also includes left-shifting
by thirty positions, not shifting at all, or causing your CPU
to overheat and melt.
So, yes: it could lead to bugs, subtle and unsubtle, just
like dividing by zero or writing to the [105] position of a
three-element array.
However, the Standard does not require the compiler to
catch every misteak in the program. Some mistakes must be
caught (in the sense that the compiler is required to produce
a diagnostic message), but not all. Some compilers will catch
more mistakes than they are required to; some will even issue
warnings about valid but "suspicious" code. It appears that
the compiler you are using doesn't catch this particular mistake;
it's not among the "must catch" mistakes, so that's permissible.
Perhaps the compiler supports different "warning levels" and
would catch this mistake if you increased its "sensitivity;"
check the documentation for the compiler to see if there's a
way to get it to be pickier.
--
Eric Sosman
es*****@acm-dot-org.invalid