+ 2
Increment/Decrement
Hey, Can someone explain to me, why the output is "0" I don't understand why the last "++" are having no influence to the result at all. https://code.sololearn.com/cCpIZIdU8AUO/?ref=app
6 Answers
+ 2
in example below
v = v // v=6
then at right side do
v++
but variable is assigned yet, and this v++ at right is lost
int v = 6;
v = v++;
System.out.println(v); //6
+ 2
Don't write code like v=v++. It leads to undefined behaviour.
+ 1
Hey Zemiak,
But this would be right also?
int v = 6;
Int x;
v = v++;
x = v;
System.out.println(v); //6
System.out.println(x); //6
So the ++ afterwards is always lost?? I was under the impression that it increments the variable right after assignment where it is used.
+ 1
I understand your intuition, but this behavior is the same for c++, c#, javaScript, php ..
Maybe this is one of the reasons why some new languages ââsuch as python or ruby ââdo not have the ++ operator.
0
// compare with this
int a=6;
a = a++ + a++;
// a; (b=a+1); c=a+b; d assign c; (e=b+1); (e lost)
// 6: (7=6+1); 13=6+7; result assign 13
System.out.println( a ); // 13
0
I still ask myself why the last ++ does nothing. Shouldn't it increase the variable after the command where it is used - so before the print out?