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?
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?
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.
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.
Have a look at the C++ operator precedence.
(++) post-increment has the highest precedence, sou you end up with (a++) + b
.