#include <iostream.h>
int main()
{
int a = 2;
int b = 3;
a++ += b;
std::cout << a;
}
My understanding of this had been that this expression would first evaluate a+b, store that value in a and then increment it. What is happening here?
#include <iostream.h>
int main()
{
int a = 2;
int b = 3;
a++ += b;
std::cout << a;
}
My understanding of this had been that this expression would first evaluate a+b, store that value in a and then increment it. What is happening here?
This is an error1:
a++ += b
because a++
returns a temporary (a pr-value) the language forbids you to modify since it is discarded as soon as the full expression has been evaluated. This is a kind of fail safe.
My understanding of this had been that this expression would first evaluate a+b, store that value in a and then increment it.
No it doesn't. According to operator precedences, ++
evaluates before +=
.
1) This answer assumes a
and b
are builtin types or well-behaved user-defined class types.
For build in types this is a compile-time-error, as asignment needs an lvalue and a++ (which is due to operator precedence evaluated first) is an rvalue. In your example the compiler will issue an error like this see compiler-explorer:
<source>: In function 'int main()':
<source>:6:9: error: lvalue required as left operand of assignment
6 | a++ += b;
| ^
Compiler returned: 1
If you have a custom type (in this case nonsense, but for demonstration) which looks like this
class A
{
public:
A operator++(int)
{
return A{};
}
A operator+=(const A&)
{
return A{};
}
int i;
};
int main()
{
A a;
A b;
a++ += b;
return 0;
}
It compiles without problems as a++ now yields a lvalue.
Aside from wrong entry point and header there are two problems with this code.
a
is defined as const
so it cannot be a lvalue, so cannot be affected by ++ or += operator.Or any assignment. It's a constant!
Increment operator++ doesn't return a lvalue as well so its result cannot be an argument of assignment operators.