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?
5 Réponses
+ 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.
+ 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
+ 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.
+ 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.
+ 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 "?" )