Increment/Decrement | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

13th Aug 2019, 9:54 PM
Rebecca D.
Rebecca D. - avatar
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
13th Aug 2019, 10:11 PM
zemiak
+ 2
Don't write code like v=v++. It leads to undefined behaviour.
14th Aug 2019, 1:36 AM
Sonic
Sonic - avatar
+ 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.
14th Aug 2019, 12:02 AM
Rebecca D.
Rebecca D. - avatar
+ 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.
14th Aug 2019, 7:58 AM
zemiak
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
14th Aug 2019, 3:31 AM
zemiak
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?
14th Aug 2019, 6:32 AM
Rebecca D.
Rebecca D. - avatar