+ 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
7 odpowiedzi
+ 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.
+ 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
+ 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.
+ 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
+ 1
WoW so mutch people has the name Lopez I also have
0
o that's mean it is the play of language's
c++ & c
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