After reading Hidden Features and Dark Corners of C++/STL on comp.lang.c++.moderated
, I was completely surprised that the following snippet compiled and worked in both Visual Studio 2008 and G++ 4.4.
Here's the code:
#include <stdio.h>
int main()
{
int x = 10;
while (x --> 0) // x goes to 0
{
printf("%d ", x);
}
}
I'd assume this is C, since it works in GCC as well. Where is this defined in the standard, and where has it come from?
-->
is not an operator. It is in fact two separate operators,--
and>
.The conditional's code decrements
x
, while returningx
's original (not decremented) value, and then compares the original value with0
using the>
operator.To better understand, the statement could be written as follows:
is how that's parsed.
That's a very complicated operator, so even ISO/IEC JTC1 (Joint Technical Committee 1) placed its description in two different parts of the C++ Standard.
Joking aside, they are two different operators:
--
and>
described respectively in §5.2.6/2 and §5.9 of the C++03 Standard.It's equivalent to
x--
(post decrement) is equivalent tox = x-1
so, the code transforms to:My compiler will print out 9876543210 when I run this code.
As expected. The
while( x-- > 0 )
actually meanswhile( x > 0)
. Thex--
post decrementsx
.is a different way of writing the same thing.
It is nice that the original looks like "while x goes to 0" though.
Anyway, we have a "goes to" operator now.
"-->"
is easy to be remembered as a direction, and "while x goes to zero" is meaning-straight.Furthermore, it is a little more efficient than
"for (x = 10; x > 0; x --)"
on some platforms.