← Back to C++ Course | Chapter 3: Operators | Lesson 7 of 9

C++ Increment & Decrement

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

cpp
#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;
}

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

cpp
#include <iostream>

int main() {
	int x = 5;
	std::cout << ++x << std::endl; // shows the incremented value: 6
	return 0;
}

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

cpp
#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;
}

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

cpp
#include <iostream>

int main() {
	int x = 5;
	std::cout << --x << std::endl; // decreases first, shows 4
	return 0;
}

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

cpp
#include <iostream>

int main() {
	int x = 5;
	std::cout << x++ << " " << x << std::endl; // prints "5 6"
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.