Why is that
x = 10, y = 10;
z = x++ + y++;
Is still 20? They have increment both but the output is still 20 why? But when i do this
z = ++x + ++y;
the output became 22. Why and how??? Someone can explain it to me? Thanks
Why is that
x = 10, y = 10;
z = x++ + y++;
Is still 20? They have increment both but the output is still 20 why? But when i do this
z = ++x + ++y;
the output became 22. Why and how??? Someone can explain it to me? Thanks
You can think of ++x and x++ as follows
static int x_plus_plus(ref int x)
{
int xp = x;
x = x+1;
return xp;
}
static int plus_plus_x(ref int x)
{
x = x+1;
return x;
}
Now, when you do x++ + y++, the values of x and y are increased by 1 but the x++ returns old x value, in case of ++x, x is increased by 1 plus (++x) makes use of the new value of x.
Look at this description by Microsoft Arithmetic operators (C# reference)
and this two examples:
i++ completes the operation first (returning its value) and increments then:
int i = 3;
Console.WriteLine(i); // output: 3
Console.WriteLine(i++); // output: 3
Console.WriteLine(i); // output: 4
While in this example (++a) the value is incrememented first and then returned.
double a = 1.5;
Console.WriteLine(a); // output: 1.5
Console.WriteLine(++a); // output: 2.5
Console.WriteLine(a); // output: 2.5