Use Pre and Post Increment/Decrement (++i, i++)
In this step, you'll learn about increment and decrement operators in C++. These operators allow you to increase or decrease a variable's value by 1, with subtle differences between pre-increment and post-increment.
Open the WebIDE and create a new file called increment_decrement.cpp
in the ~/project
directory:
touch ~/project/increment_decrement.cpp
Add the following code to the increment_decrement.cpp
file:
#include <iostream>
int main() {
// Pre-increment (++i)
int a = 5;
std::cout << "Original value of a: " << a << std::endl;
// Pre-increment: increment happens before the value is used
std::cout << "Pre-increment (++a): " << ++a << std::endl;
std::cout << "Value after pre-increment: " << a << std::endl;
// Post-increment (i++)
int b = 5;
std::cout << "\nOriginal value of b: " << b << std::endl;
// Post-increment: increment happens after the value is used
std::cout << "Post-increment (b++): " << b++ << std::endl;
std::cout << "Value after post-increment: " << b << std::endl;
// Decrement operators work similarly
int c = 5;
std::cout << "\nPre-decrement (--c): " << --c << std::endl;
int d = 5;
std::cout << "Post-decrement (d--): " << d-- << std::endl;
std::cout << "Value after post-decrement: " << d << std::endl;
return 0;
}
Compile and run the program:
g++ increment_decrement.cpp -o increment_decrement
./increment_decrement
Example output:
Original value of a: 5
Pre-increment (++a): 6
Value after pre-increment: 6
Original value of b: 5
Post-increment (b++): 5
Value after post-increment: 6
Pre-decrement (--c): 4
Post-decrement (d--): 5
Value after post-decrement: 4
Key differences:
- Pre-increment
++i
: Increments the value before it's used in the expression. In the code example, ++a
first increments a
to 6
, and then the value 6
is used in the cout
statement.
- Post-increment
i++
: Uses the current value in the expression first, and then increments the value. In the code example, b++
first uses the current value of b
which is 5
in the cout
statement, and then increments b
to 6
.
The same principles apply to decrement operators --i
and i--
, where --i
decrements first and then uses the value, and i--
uses the value first and then decrements.
Important notes:
- Pre-increment changes the value before it's used in an expression, meaning that the incremented value is immediately available for use.
- Post-increment uses the original value first, and then increments. This means that you get the original value in the current statement and the incremented value in the next.
- These operators are commonly used in loops (like
for
loops) and complex expressions where you want to modify a variable while also using its value.
- When using these operators, especially in complex expressions, it's important to keep in mind whether you need the pre- or post- version to get the intended behavior.