x = 9; x+= ++x; x - ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

x = 9; x+= ++x; x - ?

c++ claims that answer is 20, it's ok. /n But c# and java consider that answer is 19. Why? how do they logics works?

9th Feb 2017, 10:06 AM
Alexander Bystrov
Alexander Bystrov - avatar
5 Answers
+ 9
Visph and Zilvinas have provided splendid answers to this question. While both are logically correct and simply differ due to the difference in compilation process, the answers produced by compilers of different languages will always be different for the same expression and should be avoided as the code is generally annoying and unclear.
9th Feb 2017, 12:01 PM
Hatsy Rei
Hatsy Rei - avatar
+ 5
Difference is in way of interpreter/compilator handle values during evaluation of the left and right hand expressions ( guessing 'x - ?' in question is typo mistake and stand for "what's the value of x" ); with x == 9, right expression is : ++x, so firtsly x is incremented so result is 10. This result may to be assigned to the left hand expression, so add it to x, as if you have wrote: x = x + 10, so right hand expression is first evaluate: languages as C++ implicitly have already assign a new value to 'x' with the incrementation and use this new, others like C#, java and JS, seems to implicitly have 'buffered' the value of x, as they implicitly evaluate: x = x + ( ++x ); ... instead of: x = ++x; x += x; Both are logical right, just need to know what logical is used by the language used ^^ Or avoid too much shorthand expression... :P
9th Feb 2017, 11:20 AM
visph
visph - avatar
+ 4
I believe the question was asking "What is x" but in a very sloppy way. "x - ?" does not correspond to any kind of expression nor is it correct in syntax.
9th Feb 2017, 1:12 PM
Hatsy Rei
Hatsy Rei - avatar
+ 2
You should avoid such unclear code. Why make simple things complicated? This is where bugs come from and where other developers increase their "wtfs per minute" while reading your code. p.s. it's so annoying that 90% of sololearn tasks are of this kind.
9th Feb 2017, 11:36 AM
Zilvinas Steckevicius
Zilvinas Steckevicius - avatar
+ 1
Thank you, friends, for your explanations! This example is from sololearn challange. Writing "x - ?" i mean: x is ?. I consider "x = ?" logicaly incorrect, because x is not equal to "?" )
9th Feb 2017, 12:47 PM
Alexander Bystrov
Alexander Bystrov - avatar