Increment and decrement operators help you quickly add or subtract 1 from a number. They make your code shorter and easier to read.
0
0
Increment and decrement operators in C++
Introduction
When you want to count up or down by 1 in a loop.
When you need to increase or decrease a variable by 1 in a simple way.
When you want to move through items in a list one by one.
When you want to update a score or a counter quickly.
When you want to simplify code that changes a value by 1.
Syntax
C++
++variable; // adds 1 to variable --variable; // subtracts 1 from variable variable++; // adds 1 to variable after current use variable--; // subtracts 1 from variable after current use
There are two types: prefix (++variable) and postfix (variable++).
Prefix changes the value before using it, postfix changes it after.
Examples
Prefix increment adds 1 before using x.
C++
int x = 5; ++x; // x becomes 6
Postfix increment adds 1 after using y.
C++
int y = 5; y++; // y becomes 6 after this line
Prefix decrement subtracts 1 before using a.
C++
int a = 3; --a; // a becomes 2
Postfix decrement subtracts 1 after using b.
C++
int b = 3; b--; // b becomes 2 after this line
Sample Program
This program shows how prefix and postfix increments and decrements change the variable and when the change happens relative to printing.
C++
#include <iostream> int main() { int count = 0; std::cout << "Initial count: " << count << "\n"; std::cout << "Using prefix increment: " << ++count << "\n"; // count becomes 1, then prints 1 std::cout << "Using postfix increment: " << count++ << "\n"; // prints 1, then count becomes 2 std::cout << "Count after postfix increment: " << count << "\n"; // prints 2 std::cout << "Using prefix decrement: " << --count << "\n"; // count becomes 1, then prints 1 std::cout << "Using postfix decrement: " << count-- << "\n"; // prints 1, then count becomes 0 std::cout << "Count after postfix decrement: " << count << "\n"; // prints 0 return 0; }
OutputSuccess
Important Notes
Use prefix (++x) when you want the updated value immediately.
Use postfix (x++) when you want to use the original value first, then update.
Be careful when using these operators inside complex expressions to avoid confusion.
Summary
Increment (++) adds 1; decrement (--) subtracts 1.
Prefix form changes value before use; postfix changes after use.
They make counting and updating numbers simple and clean.