Skip to content
Home » Understanding the Prefix (++i) and Postfix (i++) Operators

Understanding the Prefix (++i) and Postfix (i++) Operators

woman writing on a whiteboard

There are a couple of operators that simplify how the developer writes code. But some of them aren’t trivial to read.

Two of these are the prefix (++i) and the postfix (i++) operators.

Let’s see how these two operators work.

The Prefix Operator: ++i

When you see ++i, read as increment i and then use i.

For example, let’s say you have:

int i = 0;

int result = ++i;

The above code is the same as:

int i = 0;

// Increment i
i = i + 1;

// And then use i
int result = i;

If you print the variables at the end of the execution, you’ll notice that their values will be:

i: 1
result: 1

The Postfix Operator: i++

When you see i++, read as use i and then increment i.

For example, let’s say you have:

int i = 0;

int result = i++;

The above code is the same as:

int i = 0;

// Use i
int result = i;

// And then increment i
i = i + 1;

If you print the variables at the end of the execution, you’ll notice that their values will be:

i: 1
result: 0

Merging both operators in a more complex example

Let’s say you have the following code:

int i = 4;
int j = 21;

int k = ++i * 7 + 2 - j--;

You should read the above code as:

int k = (increment i and then use i) * 7 + 2 - (use j and then decrement j)

Which is equals to:

int i = 4;
int j = 21;

i = i + 1;

int k = i * 7 + 2 - j;

j = j - 1;

If you print the variables, you’ll notice that their values will be:

i: 5
j: 20
k: 16

Conclusion

The prefix and postfix operators simplify how the developer writes code, but it might let the code more unreadable for those who aren’t familiar with them.

For you to know how to use and read them, remember:

  • i++ means use i and then increment i
  • i-- means use i and then decrement i
  • ++i means increment i and then use i
  • --i means decrement i and then use i