Hi everyone I am Irwin Lopez | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Hi everyone I am Irwin Lopez

I have a confusion in this question according to me the Answer should be 9 but why the output is 10. explain me with examples and in detail. https://www.sololearn.com/Discuss/566278/?ref=app

30th Jul 2017, 5:37 AM
Irwin Lopez
Irwin Lopez - avatar
7 Answers
+ 9
There's no left-to-right / right-to-left rule. Prefix operators are always evaluated prior to the execution of a statement. The rest of @Takshak's answer is correct.
30th Jul 2017, 6:20 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
This is because in C/C++, prefix is evaluated first. Which means in the code : int a=4, b; // Here 'a' is equals to 4 b = a + ++a; // But here 'a' pre-incrementes first, So value of 'a' now becomes 5 for both a's hence 5+5=10
30th Jul 2017, 6:03 AM
TakshakSH
TakshakSH - avatar
+ 2
A very interesting read on the topic (it was linked to in one of the stackoverflow threads): http://www.eskimo.com/~scs/readings/undef.950321.html It explains very nicely why you should NOT write such code, and generally what type of constructs you should avoid.
30th Jul 2017, 9:48 AM
Bogdan Sass
Bogdan Sass - avatar
+ 1
@Krishna - You will get the same results, no matter how many times you run it. However, that same code compiled by another compiler might produce a different result. That is what "undefined behavior" means. As for your code, you moved the space, changing the prefix increment (++a) to a postfix increment (a++). With the postfix, the increment happens after the expression is evaluated - hence the different result. It is similar to: a = 4; b = a++; //b becomes 4 vs a = 4; b = ++a; //b becomes 5
30th Jul 2017, 9:57 AM
Bogdan Sass
Bogdan Sass - avatar
+ 1
WoW so mutch people has the name Lopez I also have
30th Jul 2017, 2:48 PM
Kalebop
Kalebop - avatar
0
o that's mean it is the play of language's c++ & c
30th Jul 2017, 9:38 AM
Irwin Lopez
Irwin Lopez - avatar
0
I agree with the previous answers, but only partly. It is not true that "in C/C++, prefix is evaluated first". In reality, the result of such an operation is undefined. You cannot guarantee that you will get one answer or another. (to be more specific, there is no sequence point there, so there is no guarantee that the side effect of the prefix operation will be executed before or after the addition) For more details (including some links to more in-depth discussions of the topic) see the original thread: https://www.sololearn.com/Discuss/566278/?ref=app
30th Jul 2017, 9:45 AM
Bogdan Sass
Bogdan Sass - avatar