What is the difference between a++ and ++a?
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.
Code examples
Let’s understand the a++ operation behavior by observing the output of the following code.
#include <iostream>int main() {int a, b;// Post-incrementa = 1;b = a++;std::cout << b << " "; // prints 1std::cout << a << " "; // prints 2return 0;}
Let's discuss the above C++ code:
Line 7: assigning
1to variablea.Line 8: using the post-increment operator
a++. It increments the value ofaafter the value has been assigned tob. Therefore,bgets the original value ofa(which is 1), and thenais incremented by1.
Let’s understand the ++a operation behavior by observing the output of the following code.
#include <iostream>int main() {int a, b;// Post-incrementa = 1;b = ++a;std::cout << b << " "; // prints 1std::cout << a << " "; // prints 2return 0;}
Let's discuss the above C++ code:
Line 7: assigning
1to variablea.Line 8: using the pre-increment operator
++a. The value of the variableais first incremented and then used in the expression. This means thatais incremented by1before its value is assigned tob.
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
Free Resources