Ambiguous expression parsing in C++ syntax

Question:

There is the following valid C++ expression:

a+++b;

How should the compiler understand it: how

a + (++b);

or how

(a++) + b;

We check :

#include <iostream>
using namespace std;

int main() {
    int a = 1;
    int b = 10;
    int c = a+++b;
    cout << a << ' ' << b << ' ' << c;
    return 0;
}

2 10 11

Why would it be parsed this way? How is the preferred interpretation of +++ determined?

Answer:

There is such a principle – the lexeme is read to the maximum (this is called the rule of maximum absorption). Those. reads the first plus. Then the second. Is there such a token – ++ ? There is. So it's ++ . What's next? Another plus? Is there such a lexeme – +++ ? Ah, there is no such thing in the language? So it's ++ . The next plus is the beginning of a new lexeme… And the priority of operators has absolutely nothing to do with it.

Scroll to Top