Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c
c++
java
c#

What is the difference between a++ and ++a?

Nouman Abbasi

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

#include <iostream>
using namespace std;
int main() {
int a, b;
// Post-increment
a = 1;
b = a++;
printf("%d ", b); // prints 1
// Pre-increment
a = 1;
b = ++a;
printf("%d ", b); // prints 2
}

RELATED TAGS

c
c++
java
c#

CONTRIBUTOR

Nouman Abbasi
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring