-6
int main()
{
  int a=1;
  int b=2;
  int c=a+++b;
  cout<<"c"<<c<<endl;
}

c's value turns out to be 3. While, it gives me an error for c=a++b. What is happening here? Why does c=a+++b work?

Pallavi
  • 1
  • 1

3 Answers3

2

A key part of why a+++b "works", and a++b doesn't is the way the C and C++ language parsing is defined. It is what is called a 'greedy' parser. It will combine as many elements as possible to produce a valid token.

So, given that it's a greedy parser, a++b becomes a++ b, which is not valid. a+++b becomes a++ + b, which is syntactically valid - whether that is what you WANT is another matter. If you want to write a + +b, then you need spaces to separate the tokens.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
1

Looks like a is post increment then added to b with bad spacing. For example a++ + b. The variable a is evaluated then incremented. That being said a++b is invalid syntax.

Devin Wall
  • 180
  • 1
  • 16
1

Have a look at the C++ operator precedence.

(++) post-increment has the highest precedence, sou you end up with (a++) + b.

Derlin
  • 9,572
  • 2
  • 32
  • 53