| Author |
Why the result is 1,0
|
weyman tan
Greenhorn
Joined: Dec 19, 2011
Posts: 3
|
|
Why the result is 1, 0 in following code
is any one tell me why, thank you very much
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1778
|
|
Hello Weyman, welcome to the Ranch
An outer class cannot be declared static, so the code won't compile itself. I have removed it.
The questions tests the post fix and prefix increment operators. I have commented alongside the program the values and why it's printed so. The output I get is 0,2,1.
Next time while posting please UseCodeTags...
|
 |
weyman tan
Greenhorn
Joined: Dec 19, 2011
Posts: 3
|
|
After see your answer, I know why and the original code is
so the result is 0,1
in order to study why, I add some code in it which result is 0,2,1.
However thank you very much
|
 |
Mohamed Sanaulla
Bartender
Joined: Sep 08, 2007
Posts: 2946
|
|
|
Hi Weyman, I have added the code tags for you. Please post your code within the code tag. This makes the code more presentable.
|
Mohamed Sanaulla | My Blog
|
 |
John Stark
Ranch Hand
Joined: Jul 19, 2011
Posts: 165
|
|
so the result is 0,1
Should it give 1,0
John
|
 |
O. Ziggy
Ranch Hand
Joined: Oct 02, 2005
Posts: 430
|
|
John Jai wrote:Hello Weyman, welcome to the Ranch
I dont understand where the 1 is coming from. When it gets to this point
i = i++ + f1(i);
i is 1. So if f1 returns 0, should shouldn't i be 2 because of the i++? i.e. the output to be 0,2,2? See comments below
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 10043
|
|
I dont understand where the 1 is coming from. When it gets to this point
i = i++ + f1(i);
i is 1. So if f1 returns 0, should shouldn't i be 2 because of the i++? i.e. the output to be 0,2,2? See comments below
This more or less simplifies to
i = i++;
and we have a FAQ on why that leave i how it was...but basically, assuming i is one before we get to this line
1) we have a post-fix operator, so get the value of i. It is 1. Remember that value for a moment.
2) We now increment i, making it 2.
3) We now assign THE VALUE WE REMEMBERED to i. the value was 1, so assign 1 to i
4) i is now 1.
So for a brief, brief instant, after the increment operator but before the assignment, i IS equal to 2, but we then reset it back to 1.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
 |
|
|
subject: Why the result is 1,0
|
|
|