C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
The decrement operator receives one or two operands. It is written with the characters "--" or "-=". We use this operator in any context where statements are permitted.
Example. To start, we see a simple program written in the C# language that introduces a local variable integer called i. The character i is a classic name for a loop iteration variable. These variables are also called induction variables.
Here: We start the value stored in the variable location with the integer 100. Then, the single decrement operator -- is applied.
And: This decreases the value by one. Finally we use the -= operator and use several operands with it.
C# program that uses decrement operators using System; class Program { static void Main() { int i = 100; // Decrement by one. i--; Console.WriteLine(i); // Decrement by two. i -= 2; Console.WriteLine(i); // Decrement by negative one (add one). i -= -1; Console.WriteLine(i); // Decrement by zero (do nothing). i -= 0; Console.WriteLine(i); // Decrement by itself (results in zero). i -= i; Console.WriteLine(i); } } Output 99 97 98 98 0
Bit representation. We have already introduced the concepts of variables and values in this program. The values (such as 100) are actually stored in a bit representation format in the hardware.
And: When you apply a mathematical transformation to the integer, the resulting bit representation is changed in a well-known way as well.
Pre, post decrement. There are two forms of the decrement by one operator. These are called the post-decrement and pre-decrement operators. These forms are both considered unary operators, meaning they can only receive one operand.
Order of evaluation. When you use the post-decrement operator in an expression, the expression is evaluated before the decrement occurs. When you use the pre-decrement operator, it is evaluated after.
C# program that uses two forms of decrement using System; class Program { static void Main() { int i = 5; // This evaluates to true because the decrement occurs after the comparison. if (i-- == 5) { Console.WriteLine(true); } // This evaluates to true because the decrement occurs before the comparison. if (--i == 3) { Console.WriteLine(true); } } } Output True True
Summary. There are many different ways of decrementing variables using the decrement operators in the C# language. Please remember that you can also use expressions to decrement values, even without these operators.