+ 2
incrementation decrementation
why the result of this code is -1? int x=0; System.out.println(--x+ ++x);
5 odpowiedzi
+ 2
you are welcome.
x++ = 0
++x = 2
0 + 2 = 2
-----------
x++ = 0
______________
x++ means do something then increment value.
++x means increment value then do something.
in first example x++ + ++x it goes like this:
1. x++ = 0 (first x)
2. x++ = 1 (new x)
3. ++x = 2 (final x)
4. (first x) + (final x) => 0 + 2 = 2
+ 2
x = 0
--x = -1
++x = 0
So -1 + 0 = -1
+ 2
--x is -1 , and ++x is 0 , then -1 + 0 = -1
+ 1
Thanks for both of you, but i did not understand why:
int x=0;
System.out.println(x++ + ++x);
results 2 , and :
int x=0;
System.out.println(x++);
results zero ! :(
+ 1
I see thanks Ahmed