capypad
0 day streak
cpp / beginner
Snippet

Increment and Decrement Operators: Shorthand for Adding or Subtracting One

The increment (++) and decrement (--) operators add or subtract one from a variable. There are two forms: prefix (++a) increments before using the value, while postfix (a++) increments after using the value. This matters when the result is used in the same expression. The shorthand operators make code cleaner and are commonly used in loops. Both operators modify the variable in place, so you cannot use them on literals or expressions.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
 
int main() {
int a = 5;
int b = 5;
 
std::cout << "a before: " << a << std::endl;
std::cout << "++a after: " << ++a << std::endl;
 
std::cout << "b before: " << b << std::endl;
std::cout << "b++ after: " << b++ << std::endl;
 
std::cout << "Final values - a: " << a << ", b: " << b << std::endl;
 
int c = 10;
c--;
std::cout << "c after decrement: " << c << std::endl;
 
return 0;
}
Breakdown
1
++a
Prefix increment: increases a by 1, then returns the new value (outputs 6)
2
b++
Postfix increment: returns current value (5), then increases b to 6
3
c--
Prefix decrement: decreases c by 1 without outputting the value
4
Final values - a: 6, b: 6
Both variables end at 6 despite different increment timing