Whats the actual output?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Whats the actual output??

int x = 5,z; x = ++x; z = x + (++x); cout << z; //or sop(z) in java whats the actual problem is difference in output.In c++,output is 14 and while in java,output is 13.Can someone explain why??This led me in confusion in concepts of prefix and postfix.

2nd Nov 2017, 1:47 PM
pranit batra
pranit batra - avatar
12 Answers
+ 4
All comes down to the compiler and how it handles it for the relative language. I've seen this vary for the same language between different compilers. x = 5; x = ++x; z = x + (++x); In C++, it's doing it how I would personally think it should. X starts as 5. Next statement it's increased by 1 and stored back into X as 6. In the third statement, the ++x is forcing X to become 7 BEFORE the calculations, which causes it to change the first X to 7 also. So when the actual calculation runs, it's 7 + (7), which equals 14. In Java, it's doing mostly the same thing, except in the third statement it's only changing the (++x) to 7 before the operation and the first X is still 6. So 6 + (7) = 13.
2nd Nov 2017, 2:44 PM
AgentSmith
+ 2
You musnt have difference
2nd Nov 2017, 1:51 PM
Daniel
Daniel - avatar
+ 2
Share your both codes from your playground
2nd Nov 2017, 1:52 PM
Daniel
Daniel - avatar
+ 2
Avoid use of postfix/prefix in such statements in the practice.
2nd Nov 2017, 2:51 PM
Boris Batinkov
Boris Batinkov - avatar
+ 2
pranit, Netkos give you the answer and Boris the solution. If you change in the third statement ++x per x+1 output is the same
2nd Nov 2017, 3:54 PM
Daniel
Daniel - avatar
+ 2
Obviously, really not is the same operation because for example in JAVA: x=2 z=0 z=x+ ++x= 2+3=5 so z=5; x=3; CPP x=2 z=0 z=x+ ++x= 3+3=6 so z=6; x=3; and in both x=2 z=0 z=x +(x+1)=2 + (2+1)=5 so z=5; x=2; x=2 z=x+1 is not the same z=++x first z=3; x=2; second z=3; x=3;
2nd Nov 2017, 4:07 PM
Daniel
Daniel - avatar
+ 2
Of course ++x in this instruction z=x+(++x) work different in different languages
2nd Nov 2017, 4:09 PM
Daniel
Daniel - avatar
+ 1
ohh yes.. got it thank u guys..
2nd Nov 2017, 4:57 PM
pranit batra
pranit batra - avatar
2nd Nov 2017, 2:14 PM
pranit batra
pranit batra - avatar
0
https://code.sololearn.com/ciqB6bs67HQ2/?ref=app
2nd Nov 2017, 2:14 PM
pranit batra
pranit batra - avatar
0
Check em out..correct me if i did something wrong in coding and please explain prefix and postfix.Thanks
2nd Nov 2017, 2:15 PM
pranit batra
pranit batra - avatar
0
@Netkos Thanks man..I understood what u meant but whats the actual answer?..and why it is flawed by giving 2 different answers in different languages.This shouldnt make sense.
2nd Nov 2017, 2:49 PM
pranit batra
pranit batra - avatar