- 4

if x=5 then x++and ++x what is the result???

8th Oct 2016, 3:53 AM
Sachin Kotian
Sachin Kotian - avatar
6 Answers
+ 1
cout<<x++; //results 5 and increment the value of x but... cout<<++x; // increment the value of x and results 6
8th Oct 2016, 3:55 AM
Balaji Rs
Balaji Rs - avatar
+ 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.
8th Oct 2016, 7:24 AM
marcram
+ 1
@marcram fine
8th Oct 2016, 7:53 AM
Balaji Rs
Balaji Rs - avatar
+ 1
Ty
8th Oct 2016, 7:22 PM
Sachin Kotian
Sachin Kotian - avatar
+ 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.
11th Oct 2016, 5:32 AM
Bill
Bill - avatar
0
If x=5 ++x = 6 (increment first then display) x++ = 5 (display first then increment)
8th Oct 2016, 6:55 PM
Luis Cervantes
Luis Cervantes - avatar