In this C++ Tutorial we are going to learn about Prefix and Postfix Operators in C++,
so you can use the increment operator ++ and the decrement operator — before or after
a variable’s name. If the operator was placed before a variables’s name, it is called a
prefix operator and you can use it like this ++num. if the operator was placed after
the variable name it is called Postfix Operator, and you can use it like this num++ .
If you have a simple statement, the operators accomplish the same thing. The num
variable is increased by 1 in both statements.
1 2 |
num++ ++num |
Learn Python GUI Development
1: PyQt5 GUI Development Tutorial
2: Pyside2 GUI Development Tutorials
3: wxPython GUI Development Tutorials
4: Kivy GUI Development Tutorials
5: TKinter GUI Development Course
Also you can learn C++ GUI development with Qt5 Framework
1: Qt5 C++ GUI Development Tutorials
The usage of Prefix and Postfix Operators in C++ Tutorial becomes apparent in complex expressions
where a variable is being incremented or decremented and assigned to another
variable. The prefix operator occurs before the variable’s value is used in the expression. The
postfix is evaluated after.
So let’s look at this example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
int main() { //our variable int num = 5; //increment the variable int sum = ++num; //print the values cout << num << '\n'; cout << sum << '\n'; return 0; } |
After executing the code , the num variable and sum variable both equal to 6. The prefix
operator in ++num causes, num to be incremented from 5 to 6 before it is assigned to sum.
So this will be the result
1 2 3 |
6 6 Press any key to continue . . . |
Now let’s look at this example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include<iostream> using namespace std; int main() { //our variable int num = 5; //increment the variable int sum = num++; //print the values cout << num << '\n'; cout << sum << '\n'; return 0; } |
The result of sum is equal to 5 and num is equal to 6. The postfix operator causes num to be assigned to sum before it is incremented from 5 to 6.
So this will be the result.
1 2 3 |
6 5 Press any key to continue . . . |
Subscribe and Get Free Video Courses & Articles in your Email