Categories
c c++ code-formatting operators standards-compliance

What is the “–>” operator in C++?

9792

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);
    }
}

Output:

9 8 7 6 5 4 3 2 1 0

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?

0

    9487

    +50

    --> is not an operator. It is in fact two separate operators, -- and >.

    The conditional’s code decrements x, while returning x‘s original (not decremented) value, and then compares the original value with 0 using the > operator.

    To better understand, the statement could be written as follows:

    while( (x--) > 0 )
    

    4

    • 44

      I’ve seen it jokingly referred to as the “downto” operator (codegolf.stackexchange.com/questions/16226/…)

      May 19, 2021 at 13:26

    • 7

      I think you wouldn’t really need the parentheses around x-- though it does further enforce the separation. It would probably be enough just to associate tokens more clearly with something like while (x-- > 0).

      – paxdiablo

      Jul 3, 2021 at 1:18


    • I think, Stack Overflow needs a separate category like “C++ syntax jokes” or something like that.

      Jun 10 at 14:13

    • 1

      I think, Stack Overflow needs passing basic programming test before possibility to ask questions.

      Jul 1 at 13:27

    3707

    Or for something completely different… x slides to 0.

    while (x --\
                \
                 \
                  \
                   > 0)
         printf("%d ", x);
    

    Not so mathematical, but… every picture paints a thousand words…

    0

      2541

      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.

      0