-4

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

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 4
    Does this answer your question? [What's the difference between X = X++; vs X++;?](https://stackoverflow.com/questions/226002/whats-the-difference-between-x-x-vs-x) – asaf92 Feb 21 '21 at 11:25
  • 4
    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#increment-operator- – Dmitry Bychenko Feb 21 '21 at 11:26
  • 1
    There are two types of increment: `x++` increments `x` and returns *initial* value; `++x` increments `x` and returns *new* (incremented) value – Dmitry Bychenko Feb 21 '21 at 11:29
  • https://stackoverflow.com/questions/3346450/what-is-the-difference-between-i-and-i/3346729#3346729 is worth a read. – mjwills Feb 21 '21 at 11:45

2 Answers2

1

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.

Vaibhav D S
  • 107
  • 6
0

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
marsh-wiggle
  • 2,508
  • 3
  • 35
  • 52