Why C++ allows repeated + operators, like in x = 1 + + + + + + + + 2;

Viewed 173

To my surprise this compiles fine:

int main()
{
    constexpr int x = 1 + + + + + + 2;
    static_assert(x==3);
}

I know C++ has weird complex grammar(and it tries to allow all C code to be valid), so I presume that is the case why this is allowed, but is there some good positive reason why we would not want this code banned?

edit: even more bizzare cases work:

int main()
{
    constexpr int x = 1 + - - + + + 2;
    static_assert(x==3);
}
2 Answers

In C++ it's possible to overload operators. Boost Spirit is a particularly good use case; using the C++ grammar to represent EBNF grammars.

In such contexts, it might be useful to be able to have repeated + operators.

(A personal example: I have some cash flow modelling code that uses + to advance by a period. Naturally ++ advances by two periods. I also use << and >> to move cash between accounts. It's remarkably readable - if I might say so myself!)

It's far easier for a grammar to define unary operators

*expression*: /* other things */
              *unary-expression*
              /* more things */

*unary-expression*: + *expression*
                    - *expression*

Than

*expression*: /* other things */
              *unary-expression*
              /* more things */

*non-unary-expression*: /* other things */
                        /* more things */

*unary-expression*: + *non-unary-expression*
                    - *non-unary-expression*

Your complaint is better solved with code-review, not grammar changes

Related