Understanding x++ vs ++x | Sololearn: Learn to code for FREE!
Nowy kurs! Każdy programista powinien nauczyć się Generative AI!
Wypróbuj darmową lekcję
0

Understanding x++ vs ++x

Hi, i have this code, and i do not understand the output, i declare x=9, but it prints x=10, why? int x = 9; int y = ++x; int z = y++; Console.WriteLine("x = " + x); Console.WriteLine("y = " + y); Console.WriteLine("z = " + z); //Output: //x = 10 //y = 11 //z = 10 // BUT WHY!? ------------------------------------------------------------------------------------ int x = 9; int y = x++; int z = ++y; Console.WriteLine("x = {0}", x); Console.WriteLine("y = {0}", y); Console.WriteLine("z = {0}", z); //Output: //x = 10 //y = 10 //z = 10 // BUT WHY!?

8th Feb 2017, 8:59 AM
Kenneth Bore Eilertsen
Kenneth Bore Eilertsen - avatar
4 odpowiedzi
+ 4
Well a simple thing. x++ use value of x then increases its value I.e. use then increases ++x first increase then use the value.
8th Feb 2017, 9:27 AM
Megatron
Megatron - avatar
+ 1
x++ can be treated as shortcut for x = x + 1 but with some magic. If you use x++ value is evaluated in equation then incremented, but if you use ++x value is increased first, then evaluated. So in declaration of y you also increment x, that's why it outputs 10. In first code you first increment then assign the value to y. In second code you first assign the current value of x then increment x. That's why u get different results for both codes
8th Feb 2017, 9:06 AM
Mieszko Mieruński
Mieszko Mieruński - avatar
+ 1
You could also write y = x +1 so it wouldn't change value of x ;)
8th Feb 2017, 9:21 AM
Mieszko Mieruński
Mieszko Mieruński - avatar
0
Ok, i solved it, the reason i allways get that x=10 is because i increment x before i print. This, allthough messy, would output what i want: int x = 9; Console.WriteLine(x); int y = ++x; Console.WriteLine(y); int z = ++y; Console.WriteLine(z); //Output: //x = 9 //y = 10 //z = 11
8th Feb 2017, 9:19 AM
Kenneth Bore Eilertsen
Kenneth Bore Eilertsen - avatar