- 4
if x=5 then x++and ++x what is the result???
6 Answers
+ 1
cout<<x++; //results 5 and increment the value of x
but...
cout<<++x; // increment the value of x and results 6
+ 1
@Balaji, it's better that you specify that you are writing two alternatives, because in case of two consecutive statements, as it seems, the final result is 7.
+ 1
@marcram fine
+ 1
Ty
+ 1
The question has been asked previously and I have posted an answer there. I am copying the answer here too. Hope it helps.
The correct answer is : undefined behavior. That is: the result depends.
There is no rule in c++ that specifies the order of evaluation of operands of an operator. So i++ can be evaluated first this time and may be evaluated after ++i next time.
You may be confused: why 1+2-3 is evaluated from left to right?
The answer is: that's the associativity of operators, not the evaluation sequence.
This is one of the few subtle things one should be aware of when programming with c++.
Go to cppreference.com and look for Order of evaluation for more details. You will see the exact expression on the page. It is explicitly tagged as undefined behavior.
0
If x=5
++x = 6 (increment first then display)
x++ = 5 (display first then increment)