Increment operator and decrement operator

++ is called the increment operator, and -- is called the decrement operator.

Increment operator adds one to the operand.

Decrement operator subtracts one from the operand.


using System;

class Program
{
    static void Main(string[] args)
    {
        int i = 4;

        i++;
        Console.WriteLine(i);
        ++i;
        Console.WriteLine(i);

        i--;
        Console.WriteLine(i);

        --i;
        Console.WriteLine(i);

    }
}

The output:


5
6
5
4

As you can see from the code above, the increment operator and decrement operator can be either before the operand or after the operand.

The difference is when to update the operand.


y = x++;

is


y = x;
x = x +1;

while


y = ++x;

is


x = x + 1;
y = x;

The following code illustrates the difference between prefix or suffix of the increment operator and decrement operator.


using System;

class Program
{
    static void Main(string[] args)
    {
        int i = 4;
        int y = 0;
        
        y = i++;
        Console.WriteLine("i = " + i);
        Console.WriteLine("y = " + y);
        Console.WriteLine();

        ++i;
        Console.WriteLine("i = " + i);
        Console.WriteLine("y = " + y);
        Console.WriteLine();

        y = i--;
        Console.WriteLine("i = " + i);
        Console.WriteLine("y = " + y);
        Console.WriteLine();

        y = --i;
        Console.WriteLine("i = " + i);
        Console.WriteLine("y = " + y);

    }
}

The output:


i = 5
y = 4

i = 6
y = 4

i = 5
y = 6

i = 4
y = 4
java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.