What is the difference between a++ and ++a in coding?
The answer to this question is very simple.
- ++a means first change then use the variable.
- a++ means first use then change the value of variable.
Both a++ and ++a basically performs the same function: they increase the value of variable a by 1. But having said that, the post-increment(a++) and the pre-increment(++a) operators work differently.
When we assign a++ to any variable, it takes the current value of a, and then increments the value of a.
When we assign ++a to any variable, it first increments the value of a, and then assigns it to the variable.
For example, here is a snippet of code in C++:
int a=1; //storing a number in a
int x=a++; //using the post-increment operator
cout<<”x =”<<x<<endl; //displays current value of x
cout<<”a =”<<a; //displays current value of a
The output is:
x =1
a =2
Whereas, when we see the next snippet of code,
int a=1; //storing a number in a
int x=++a; //using the pre-increment operator
cout<<”x =”<<x<<endl; //displays current value of x
cout<<”a =”<<a; //displays current value of a
The output is:
x =2
a =2
Hope the above example clear the concept of the difference between a++ and ++a in coding.
One Reply to “What is the difference between a++ and ++a in coding?”
Comments are closed.