What is the output of the code: | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

What is the output of the code:

int x=1; cout <<(x++ + ++x); cout <<x;

26th Dec 2017, 7:10 PM
shivansh agarwal
shivansh agarwal - avatar
7 Answers
+ 4
43
29th Dec 2017, 3:25 AM
$hardul B
$hardul B - avatar
+ 4
As x++ first gives number then increments while ++x will increment then give number..
29th Dec 2017, 3:28 AM
$hardul B
$hardul B - avatar
27th Dec 2017, 5:42 AM
deFault
+ 1
26th Dec 2017, 7:29 PM
Yesh Jadav
Yesh Jadav - avatar
+ 1
4
26th Dec 2017, 7:30 PM
shivansh agarwal
shivansh agarwal - avatar
+ 1
yes
26th Dec 2017, 7:37 PM
Yesh Jadav
Yesh Jadav - avatar
+ 1
@$hardul Birje, (x++ + ++x) produces undefined behavior. The expression modifies x twice in one sequence point. This produces undefined behaviour. And UB means that literally anything can happen. See the links from the answer, I've linked here, for more info on this topic. But in a nutshell, sequence point in c++ is a point where you may be sure, that all the side effects of all the operations, performed before it, have taken effect. For example, if you write x++, you may be sure that x is incremented, only at the next SP. Changing something more then once, during one SP, results in UB. There is a complete list of things that do and don't create SP in c++, somewhere in the links I've provided in the linked answer below/above. For example, arithmetic operators or function parameter separator "," don't, end of statement (;), comma operator - do.
29th Dec 2017, 11:47 AM
deFault