0

i got final tomorrow & stuck in this question .

Let's say ( c++ )

x = 1;
cout << ++x + ++x; // this gives me equals to 6 !

isn't it suppose to be 5 ? ( 2 + 3 ) i'm lost , any help would be truly appreciated .

Kok Sin
  • 1
  • 1
  • Possible duplicate of [Why are these constructs (using ++) undefined behavior in C?](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior-in-c) – David Heffernan Jun 11 '18 at 18:19

1 Answers1

-1

It's like :

the first ++x = 2

so now x=2
next ++x = 3
now x=3

so out = 3 + 3 = 6

because you are using the same variable so it will be applied to both the x.

  • But when should i apply this method of calculation ? – Kok Sin Sep 18 '15 at 16:05
  • @KokSin, you need to consider that you are using the same variable name, so if you change x anywhere it will apply where ever u used the same x in that particular scope. – Nandlal Kumar Sep 18 '15 at 18:11
  • the same will have different result if you use something like : ++x + ++y – Nandlal Kumar Sep 18 '15 at 18:12
  • No. Its a technical statement. The code's behaviour is undefined and thus cannot be reasoned about. – David Heffernan Jun 15 '18 at 06:19
  • @DavidHeffernan Do you see everyone's post which was posted 2 years back and give them negative votes. Doesn't matter for me, i am here for answer if i have any doubt and help someone if i could. – Nandlal Kumar Jun 15 '18 at 06:25
  • So now you have your answer. You know know that your post was wrong and that this code is UB. I'm glad I could help you. – David Heffernan Jun 15 '18 at 06:32
  • No. It was me that told you that it was wrong. It seems like you are more concerned with the voting that the technical matters. – David Heffernan Jun 15 '18 at 06:41
  • it all depends on perception, i still see it right. BTW i am not concerned with voting, i am just surprised that someone has enough time to see your old post just give a negative vote without proper explanations. – Nandlal Kumar Jun 15 '18 at 06:47
  • It's wrong. Perception is not part of it at all. Simple facts. It's undefined behaviour. UB. You do know what UB is right? As for proper explanations I left a comment and provided a duplicate in my close vote. Presumably you followed the link to the duplicate? – David Heffernan Jun 15 '18 at 06:56