Previous Page
Next Page

Incrementing and Decrementing Variables

If you wanted to add 1 to a variable, you could use the + operator:

count = count + 1;

However, it is unlikely that an experienced programmer would write code like this. Adding 1 to a variable is so common that in C#, you can do it with the ++ operator. To increment the variable count by 1, write the following statement:

count++;

Similarly, subtracting 1 from a variable is so common that in C# you can do it with the –– operator. To decrement the variable count by one, write this statement:

count--;
NOTE
The ++ and – – operators are unary operators, meaning that they take only a single operand. Theyshare the same precedence and left associativity as the ! unary operator, which is discussed in Chapter 4, “Using Decision Statements.”

The following table shows you how to use these two operators.

Don't write this

Write this

variable = variable + 1;
variable++;
variable = variable - 1;
variable--;


Previous Page
Next Page