Image for post
Image for post

What is the difference between ++i vs. i++ ?

Pre/Post Increment/Decrement Operators Explained.

Increment Operator ++

If you have a basic understanding of any programming language then you’re likely familiar with for loops and have probably used the ‘++’ operator. The increment operator written as ‘++’ adds one to its operand and the decrement operator ‘ — — ’ subtracts one from its operand.

Languages that support the ++/ — — increment/decrement operators include: C++, C#, Go, Java, JavaScript, PHP and more.

for (var i = 0; i < 3; i++) {
console.log(i);
}
Output:
0 // i = 0, increment by 1 => i = 1
1 // i = 1, increment by 1 => i = 2
2 // i = 2, increment by 1 => i = 3, i is not < 3, loop ends

Pre-increment vs. Post-increment

You’re probably wondering, if the increment operator adds one to the operand, aren’t ++i and i++ the same? Yes, as a standalone statement they are equal. Both a pre-incremented operand ++i, and a post-incremented operand i++, where i is the operand will both add one to i. So is there a difference? Yes.

The difference can be seen if the incremented operand is assigned to a variable, the value of the assigned variable will depend on whether the operator is pre- or post-incremented.

As a quick reminder, all programming languages execute code in order. It runs one line of code at a time, and code is loaded into memory in the order specified starting on line 1.

Pre-increment ++i

  • increment the variable
  • the value of the expression is the final value

Post-increment i++

  • the original value is loaded into memory, then increment the variable
  • the value of the expression is the original value
// Increment operator
// Pre-increment: x is incremented by 1, then y is assigned the value of x
x = 1;
y = ++x; // x is 2, y is also 2

// Post-increment: y is assigned the value of x, then x is incremented by 1
x = 1;
y = x++; // x is 2, y is 1

// Decrement operator
// Pre-decrement: x is decremented by 1, then y is assigned the value of x
x = 1;
y = --x; // x is 0, y is also 0

// Post-decrement: y is assigned the value of x, then x is decremented by 1
x = 1;
y = x--; // x is 0, y is 1

In languages that don’t support this operator, you can increment as you would using simple addition and subtraction.

# Pre-increment: y = ++x
x = 1
x = x + 1 # x is now 2 (or "x += 1" in Python and Ruby)
y = x # y is also 2

# Post-increment: y = x++
x = 1
y = x # y is 1
x = x + 1 # x is now 2

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store