Popular languages, like C, C++ and Java, have increment ++
and decrement --
operators that allow you to increment and decrement variable values.
To increment a value, you can do a++
(post-increment) or ++a
(pre-increment):
int a = 1;
a++;
printf("%d", a); // prints 2
int a = 1;
++a;
printf("%d", a); // prints 2
It seems as though the operator’s position before or after the variable name does not make any difference.
However, the ++
position can make a difference when you are reading the value of the variable in the same statement. More precisely, the post-increment a++
and the pre-increment ++a
have different precedence.
For example:
int a = 1;
int b = a++;
printf("%d", b); // prints 1
int a = 1;
int b = ++a;
printf("%d", b); // prints 2
As you can see, a++
returns the value of a
before incrementing, and ++a
returns the value of a
after it has been incremented.
Let’s understand the a++
operation behavior by observing the output of the following code.
Let's discuss the above C++ code:
Line 7: assigning 1
to variable a
.
Line 8: using the post-increment operator a++
. It increments the value of a
after the value has been assigned to b
. Therefore, b
gets the original value of a
(which is 1), and then a
is incremented by 1
.
Let’s understand the ++a
operation behavior by observing the output of the following code.
Let's discuss the above C++ code:
Line 7: assigning 1
to variable a
.
Line 8: using the pre-increment operator ++a
. The value of the variable a
is first incremented and then used in the expression. This means that a
is incremented by 1
before its value is assigned to b
.
Quiz!
What is the output of the following C++ code snippet?
#include <iostream>
int main() {
int a = 5;
int b = 10;
std::cout << a++-++b;
return 0;
}
6
-6