cpp / beginner
Snippet
Increment and Decrement Operators
The increment operator (++) adds 1 to a variable, while decrement (--) subtracts 1. The position of these operators matters significantly: prefix (++x) increases the value then returns it, while postfix (x++) returns the original value then increases it. This distinction affects the result of expressions in subtle but important ways.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>int main() {int a = 5;int b = 5;std::cout << "a++ = " << a++ << std::endl;std::cout << "After a++: " << a << std::endl;std::cout << "++b = " << ++b << std::endl;std::cout << "After ++b: " << b << std::endl;return 0;}
Breakdown
1
a++ returns 5, then increments to 6
Postfix: value is used before increment
2
++b increments to 6, then returns 6
Prefix: value is incremented before use
3
Output: a++ = 5, a = 6, ++b = 6, b = 6
Shows how position affects the output