问题
i have small doubt.why the below code is printing value i=2.
int i=2;
i=i++;
System.out.println(i);
can someone please explain me what is happening in line no 2.
so there is no meaning here of doing ++ here?
Thanks
回答1:
i=i++;
Because first the assignment happens, then the increment applies.
Something like:
first i gets 2, then ++ operation happens, but results won't be re-assigned to i, so i value will remain as 2.
回答2:
i = i++;
first evaluates the i++
expression, which increments i
and evaluates to the value of i
prior to the increment. Since you immediately assign to i
this value, it resets the value of i
so the increment appears to never have happened. i = ++i;
would cause the other behavior.
回答3:
When you are telling i=i++;
you are telling the computer to assign i to i, and after that, increment i's value, but it will not affect i, because i's value is 2.
The correct way to do it should be i=++i;
meaning, add 1 to i before assigning it to i, or you could simply use i++;
回答4:
Thanks to all for helping me in understanding the things which was of great value.
I found somewhere nice post on this.
I got the answer from the suggestion given by stackoverflow forum only but there was some clear explanation missing what I feel.
Miljen Mikic suggested link is not working and saying page not found.
Some Clear explanation given for problem below is
int a=2, b=2;
int c = a++/b++;
System.out.println(c);
disassembles to the following.
0:iconst_2 ; [I]Push the constant 2 on the stack[/I]
1:istore_1 ; [I]Pop the stack into local variable 1 (a)[/I]
2:iconst_2 ; [I]Push the constant 2 on the stack, again[/I]
3:istore_2 ; [I]Pop the stack into local variable 2 (b)[/I]
4:iload_1 ; [I]Push the value of a on the stack[/I]
5:iinc1, 1 ; [I]Add 1 to local variable 1 (a)[/I]
8:iload_2 ; [I]Push the value of b on the stack[/I]
9:iinc2, 1 ; [I]Add 1 to local variable 2 (b)[/I]
12:idiv ; [I]Pop two ints off the stack, divide, push result[/I]
13:istore_3 ; [I]Pop the stack into local variable 3 (c)[/I]
14:return
which help me understand much better.
Please add to this If I am wrong in my point.
Thanks for all your answers.
来源:https://stackoverflow.com/questions/12147631/post-increment-behaviour