C++ Increment & Decrement
In this page:
Postfix Increment Operator
Postfix x++ returns x's current value for use in the surrounding expression first, and only afterward increases the actual variable by 1. This distinction matters when the operator is used inline, like arr[i++], which accesses index i before i gets incremented.
Example: Postfix Increment Operator
#include <iostream>
int main() {
int arr[3] = {10, 20, 30};
int i = 0;
std::cout << arr[i++] << std::endl; // accesses index 0, then i becomes 1
std::cout << i << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Prefix Increment Operator
Prefix ++x increases the variable immediately and then returns that already-updated value, which is why cout << ++x; shows the incremented value, while cout << x++; would show the value before incrementing. For simple standalone statements like x++; on its own line, prefix and postfix behave identically since nothing uses the returned value.
Example: Prefix Increment Operator
#include <iostream>
int main() {
int x = 5;
std::cout << ++x << std::endl; // shows the incremented value: 6
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Postfix Decrement Operator
Postfix x-- mirrors postfix increment: it returns the current value for immediate use, then decreases the variable afterward. This ordering is important in loops that count down while also using the pre-decrement value, such as processing the last element of an array before moving to the next.
Example: Postfix Decrement Operator
#include <iostream>
int main() {
int x = 5;
std::cout << x-- << std::endl; // shows 5, then x becomes 4
std::cout << x << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Prefix Decrement Operator
Prefix --x decreases the variable first and returns the already-reduced value, the decrement counterpart to prefix ++x. As with increment, the prefix/postfix distinction only actually changes behavior when the operator's return value is used somewhere else in the same expression.
Example: Prefix Decrement Operator
#include <iostream>
int main() {
int x = 5;
std::cout << --x << std::endl; // decreases first, shows 4
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Operators inside Outputs
Testing these operators inside cout statements is a quick way to see the prefix/postfix difference for yourself: cout << x++ << " " << x; will print the original value followed by the incremented one, making the timing of the update visible rather than just theoretical.
Example: Operators inside Outputs
#include <iostream>
int main() {
int x = 5;
std::cout << x++ << " " << x << std::endl; // prints "5 6"
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: