>> actually do?
This question already has an answer here:
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.
When x
is 1 then the post-decrement reduces it to 0 and the resultant value of bitshifting that is 0, which will cause the loop to terminate.
More generally, if you try to use >>
on a negative value (eg 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).
while( x -->> 0 ) // x runs to 0
No, the "goes to operator" is -->
with only one >
sign. It decreases x
by one and then compares the result to zero.
The -- >> 0
"runs to operator" decreases x
and then bitshifts the result rightward by zero. Bitshifting by zero does nothing for nonnegative x
, otherwise it's implementation-defined (usually does nothing, but could be random). Zero bitshifted by zero is zero, which is interpreted as false
, at which point the loop will terminate.
So it "works" but it's a terrible way of expressing a loop.
- 递减,但在递减之前返回变量的值,>>右移右边的操作数,即0(也称为非操作数),然后隐式地将结果与0进行比较。
链接地址: http://www.djcxy.com/p/1974.html上一篇: “+ +”运算符的含义(不是++)
下一篇: >>其实呢?