1

I've been searching for this question but they don't really explain my doubt.

int x = 5;

x += ++x;
cout << x;

Answer is 12 instead of 11 (which I thought to be), I came to the conclusion that the ++x is done first right? Means x = 6. Followed by the 6 + 6 = 12. Am I assuming in the right direction?

and

x += x++; //= x + (x++)
cout << x;

Answer is 11, I came to the conclusion that it's = 6 + 5 = 11, am I right?

what about

++x += ++x;
cout<< x;

Answer is 14, so does it mean that the right ++x comes first. Which makes x = 6. Then the left ++x comes into play, which makes x = 7 at this time. After which it process 7 + 7 = 14.

Is this the right assumption?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 1
    you're correct in your conclusion. Look here: http://en.cppreference.com/w/cpp/language/operator_precedence – Vinbot Jul 30 '14 at 17:04
  • 2
    Possible duplicate of http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points – eerorika Jul 30 '14 at 17:07
  • `x + ++x` (and `x + x++`, and by extension, `x += ++x` and `x += x++`) involves undefined behavior. It could come out equal to 42 if it wanted, or crash the program, or open a wormhole, etc etc etc. – cHao Jul 30 '14 at 17:07
  • As a side note, don't ever use any of the assignments above in real code (unless you're trying to encrypt it). As a second side note, if you know it's wrong to begin with, then there's no point asking about it. – barak manos Jul 30 '14 at 17:08
  • @Vinbot: You are wrong. You should have gone for http://en.cppreference.com/w/cpp/language/eval_order – Deduplicator Jul 30 '14 at 17:09
  • it's funny that `++x` will also affect the `x` on the left of the equal sign... have you defined custom `++` operators? Wouldn't they add the value to a copy of the variable instead of changing the variable itself? – Félix Adriyel Gagnon-Grenier Jul 30 '14 at 17:11
  • 1
    @FélixGagnon-Grenier: `int` is a primitive type, no custom operators possible. – Deduplicator Jul 30 '14 at 17:13
  • ++ is a unary Operator and +(Addition) is binary and Unary always takes precedence over binary. so the compiler executes unary first Right to left. check this out (http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm) – batman Jul 30 '14 at 17:17
  • @NarendraDubey You are wrong, read the duplicate. – juanchopanza Jul 30 '14 at 18:07
  • @juanchopanza sorry for my limited knowledge...and honored to have great people like You..thanks!! – batman Jul 30 '14 at 18:39

0 Answers0