4

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.

codeling
  • 11,056
  • 4
  • 42
  • 71
Devesh Agrawal
  • 8,982
  • 16
  • 82
  • 131
  • 1
    Stepping through with a debugger would help you here. – benjymous Oct 25 '13 at 08:07
  • 3
    You are not [trying to compile this with a C compiler](http://stackoverflow.com/a/10654019/335858), are you? – Sergey Kalinichenko Oct 25 '13 at 08:08
  • 3
    I'm pretty sure this is would be undefined behaviour due to sequencing. – Bathsheba Oct 25 '13 at 08:13
  • @Bathsheba aren't parentheses enough to ensure the proper sequencing? – Dariusz Oct 25 '13 at 08:14
  • @Dariusz No, parentheses only ensure associativity. – jrok Oct 25 '13 at 08:15
  • According to the C++ standard your problem is undefined behavior because of missing sequence points but the real problem is just that you tried to be clever (always dangerous when programming) and tried to stuff too much in one line. Don't do that. It makes your code unreadable. – Sarien Oct 25 '13 at 08:21
  • @Sarien that's why the [Keep it Simple, Stupid](http://en.wikipedia.org/wiki/KISS_principle) should always be used. – Dariusz Oct 25 '13 at 08:23

1 Answers1

5

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!)

masoud
  • 55,379
  • 16
  • 141
  • 208
  • @jrok: Thanks, I didn't notice that at first. Edited. – masoud Oct 25 '13 at 08:21
  • 1
    Don't thank me too soon, I'm actualy not sure anymore. :) *"In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.* I'm pretty sure it was undefined in C++03, but this quote is from C++11. – jrok Oct 25 '13 at 08:21
  • @jrok: So you can ask a great question in SO about that and you have my +1 for that :-) – masoud Oct 25 '13 at 08:25