while( x -->> 0 ) // x runs to 0
This is actually a hybrid of the --
(post-decrement) and >>
(bitshift right) operators, better formatted as:
while (x-- >> 0) ...
For this specific usage, with 0 on the right hand side, x
is decremented with each loop iteration due to the postfix --
, and the prior (pre-decrement) value is shifted right 0 bits by >> 0
which does nothing at all when x
is non-negative, so the statement could be simplified to:
while (x--) ...
When x
is 1 that's non-zero so found true
for the purposes of the while
test, then post-decrement reduces it to 0 and the loop executes for the last time (with x
being 0 during that iteration); the next time while (x--)
is checked with x
already 0, the while loop terminates, with x
left wrapping to the highest representable value for the unsigned type.
More generally, if you try to use >>
on a negative value (e.g. x
starts at 0 or a negative value great than INT_MIN
, so x--
yields a negative value) the result is implementation defined, which means you have to consult your compiler documentation. You could use your compiler documentation to reason about how it would behave in the loop....
Relevant part of the Standard: 5.8/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 non-negative value, the value of the result is the integral part of the quotient of E1/2^E2
. If E1
has a signed type and a negative value, the resulting value is implementation-defined.
BTW /- for Visual Studio, per http://msdn.microsoft.com/en-us/library/336xbhcz.aspx, the implementation defined behaviour is "No shift operation is performed if additive-expression is 0.". I can't find anything in the GCC manual about this (would have expected it here).