QuinVon
QuinVon

Reputation: 47

Why my integer number assignment is invalid?

This is my test code,it's very simple:

  class Program
    {
        static void Main(string[] args)
        {
            int number = 0;
            int newNumber = number++;
            Console.WriteLine("the old number is {0},the new number is:{1}", number, newNumber);
            Console.Read();
        }
    }

whereas the output result is:'the old number is 1,the new number is:0',I think it's opposite with the result I want.

Upvotes: 0

Views: 168

Answers (3)

jahnavi13
jahnavi13

Reputation: 42

Here, you have used number++ which is Post increment operator. It assigns the value first and then increments its value. You can achieve your desired output in two ways :

  1. Use Pre increment operator

    int newNumber = ++number;

  2. Simply adding 1 to number variable and then assigning it to newNumber

    int newNumber = number + 1;

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

That is because number++ updates the value of number by incrementing it (PostFix). This is done after using the original value in the expression it is used. To achieve the desired behaviour, You can use:

int number = 0;
int newNumber = number + 1;

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190945

using the postfix increment ++ operator, it first returns the original value, then increments. To get what you want use the prefix increment operator like

 int newNumber = ++number;

But if you don't want to change number, don't use an incrementing operator, use addition/subtraction instead.

Upvotes: 3

Related Questions