[edit] C# Increment and Decrement Operators
C# increment and decrement operators are denoted by the ++ or -- symbols in front or behind the variable'
Here is a chart of how the increment and decrement operators work
C# increment and decrement operators
|
Name |
Operator |
X = 100 |
Y |
|
Pre-increment |
++X |
101 |
101 |
|
Post-increment |
X++ |
100 |
101 |
|
Pre-decrement |
--X |
99 |
99 |
|
Post-decrement |
X-- |
100 |
99 |
We will give you an example of real c# code.
Output:
using System;
class Program
{
static void Main(string[] args)
{
int y;
int a = 100;
y = ++a; //pre-increment
Console.WriteLine("y = " + y + " and a = " + a);
//y=101 and a=101
y = a++; //post-increment
Console.WriteLine("y = " + y + " and a = " + a);
//y=101 and a=102
Console.Read();
}
}
As you can see post-increment and pre-increment will always increment variable a. Post-increment will NOT change the left side of the expression which is variable y in the code above.
|