Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
hi The under code should return 15 but in C# return value is 14 !!!
why in C# return value is 14

C#
int x = 2;
int y =x+ 4* ++x;
MessageBox.Show(x.ToString()+"\n"+y.ToString());
Posted
Updated 23-Oct-11 6:29am
Comments
Sergey Alexandrovich Kryukov 23-Oct-11 23:25pm    
Where is a logical operator?!
--SA

14 is correct

For the left x=2 + 4 * (increment x =3) -> 2+ 4*3 -> 14
 
Share this answer
 
Comments
Abhinav S 23-Oct-11 12:34pm    
Similar answer to mine. My 5.
Espen Harlinn 23-Oct-11 18:01pm    
Right :)
Mehdi and Abhinav are correct.
The result is also 14 in Java.
It is identical to y = x + 4 * (x+=1);

The expressions are evaluated left to right.
You will get 15 if the left x is moved to the right, y = 4 * ++x + x;
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 23-Oct-11 23:24pm    
Finally, an answer with some explanation, my 5.
--SA
int y =x+ 4* ++x;
This can be simplified to y = x + 4 * (x+1).

++x is a prefix unary operator. So the 1 is first added and then it used for further calculation.
As a result expression becomes 2 + 4 * (2 + 1) and hence 14.
 
Share this answer
 
Comments
Mehdi Gholam 23-Oct-11 12:35pm    
my 5!
Abhinav S 23-Oct-11 12:36pm    
Thank you.
Espen Harlinn 23-Oct-11 18:01pm    
Right :)
Abhinav S 24-Oct-11 1:13am    
Thanks.
BillWoodruff 24-Oct-11 0:22am    
Spot on Abhhinav-ji ! It is interesting to me that looking at this expression my mind somehow wants to imagine that the unary ++ prefix operator gets precedence and then modifies the value of the 'x variable at the start: but the moment I think of the compiler as stuffing the value of the first 'x in a register, reality comes back into 'focus.'

How have I missed being aware of ++ used as as a prefix ? :) ... duh ...
No The left x in line two is 3
This code in java return value is 15
 
Share this answer
 
Comments
Mehdi Gholam 23-Oct-11 12:36pm    
Use the comments if you need further assistance, don't post answers.
f.zeinali 23-Oct-11 12:45pm    
plz run this code
<pre lang="c#">
int x = 2;
int y = ++x;
MessageBox.Show(x.ToString()+"\n"+y.ToString());
</pre>
The result is
x=3
y=3
Mehdi Gholam 23-Oct-11 12:38pm    
I doubt that, all operation are done from the left unless you have '(', to get 15 use x+(4*++x)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900