C++ Increment and Decrement Operators
Increment and decrement operators in C++ are used to increase or decrease the value of a variable by 1. They are commonly used in loops and iterative operations.
Types of Increment and Decrement Operators
| Operator | Description | Example |
|---|---|---|
| ++ (Prefix) | Increments the value by 1 before using it in an expression | int x = 5; int y = ++x; // x=6, y=6 |
| ++ (Postfix) | Increments the value by 1 after using it in an expression | int x = 5; int y = x++; // x=6, y=5 |
| — (Prefix) | Decrements the value by 1 before using it in an expression | int x = 5; int y = –x; // x=4, y=4 |
| — (Postfix) | Decrements the value by 1 after using it in an expression | int x = 5; int y = x–; // x=4, y=5 |
Example Program
#include <iostream>
using namespace std;
int main() {
int a = 5, b;
// Prefix increment
b = ++a; // a=6, b=6
cout << "After prefix ++: a=" << a << ", b=" << b << endl;
// Postfix increment
a = 5; // reset
b = a++; // a=6, b=5
cout << "After postfix ++: a=" << a << ", b=" << b << endl;
// Prefix decrement
a = 5;
b = --a; // a=4, b=4
cout << "After prefix --: a=" << a << ", b=" << b << endl;
// Postfix decrement
a = 5;
b = a--; // a=4, b=5
cout << "After postfix --: a=" << a << ", b=" << b << endl;
return 0;
}
Output
After prefix ++: a=6, b=6 After postfix ++: a=6, b=5 After prefix --: a=4, b=4 After postfix --: a=4, b=5
Important Notes
- Prefix operators (++a / –a) change the variable before using it in an expression.
- Postfix operators (a++ / a–) change the variable after using it in an expression.
- Increment and decrement operators are widely used in for loops and iterative operations.
Next Topic
Next, you can learn about C++ Operator Precedence to understand the order in which operators are evaluated in expressions.