Reputation: 9212
I am feeling very stupid to asking this question. but cant figure out the reason on my own.
int main()
{
int target;
int buffer =10;
const int source = 15;
target = (buffer+=source) = 20;
cout << target+buffer;
return 0;
}
target = (buffer+=source) = 20;
will become target = (25) = 20
.
But if I am giving same statement in my source file, it is giving l-value error.
How the value of target+buffer
is printing 40.
Upvotes: 4
Views: 141
Reputation: 56509
Some predefined operators, such as +=, require an operand to be an lvalue when applied to basic types [§13.5/7]
buffer+=source
returns a lvalue reference to buffer
. So you have not compile error.
your statement can be evaluate as:
buffer+=source;
buffer=20;
target=20;
But modifying buffer
twice in a statement is undefined behavior and another compiler can evaluate something else as result. (Not sure in this case also!)
Upvotes: 5