Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
like image 326
NoSenseEtAl Avatar asked Jan 24 '23 09:01

NoSenseEtAl


1 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!)

like image 94
Bathsheba Avatar answered Jan 26 '23 22:01

Bathsheba