0

Visual Basic and C# Just learning the basics and the output from these very simple few lines confuses me.

int x = 10;
int y = x++;
Console.WriteLine(x);
Console.WriteLine(y);

The output is 11 and then 10. I was expect 10, then 11. What am I missing here?

JoOFly
  • 9
  • 1
  • 1
    `x++` means as; _return `x` **then** increment its value_. That's why when you write them `x` will be `11` but `y` will be `10`. – Soner Gönül Sep 07 '15 at 10:39
  • 1
    `int y = x++;` assign 10 to `y` because you use `x++`(postfix increment) instead of `++x`(prefix increment). But **after** this `x` is changed to `11`. See: [++ Operator](https://msdn.microsoft.com/en-us/library/36x43w8w.aspx) – Tim Schmelter Sep 07 '15 at 10:39
  • Thank you and apologies for duplicate – JoOFly Sep 07 '15 at 10:46

2 Answers2

2

x++ increments x after its usage (so in your example after assigning its current value to y). ++x on the other hand increments x before it is used. So

int x = 10;
int y = ++x;   // Note that the plus signs stand before x, not after!
Console.WriteLine(x);
Console.WriteLine(y);

would lead to

11

11

If you want to assign x+1 (11) to y and leave x at 10 do

int x = 10;
int y = x + 1;
Console.WriteLine(x);
Console.WriteLine(y);

10

11

nozzleman
  • 9,529
  • 4
  • 37
  • 58
0

y = x++ will assign first and then increment. y = ++x will increment first, then assign. In your example, you are first assigning y the value of x, then incrementing x to 11.

As int is a value type (compared to a reference type), changing the value of x won't affect the value assigned to y.

int x = 10;
int y = x++; // Assigns the value of x to y (i.e. 10), THEN incrementing x to 11.
Console.WriteLine(x); // Writes the current value of x (i.e. 11).
Console.WriteLine(y); // Writes the current value of y (i.e. 10).
Micke
  • 2,251
  • 5
  • 33
  • 48