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

Asked

Viewed 6,957 times

10

I found an excerpt of code in an application that I’m continuing that I hadn’t seen before (or never noticed). Casually I always used i++ in a loop of repetition, for example, however this passage contained ++i and I didn’t notice any difference in the result. See below an example:

public static void main(String[] args) {
    for (int i = 0; i < 10; ++i) {
        System.out.println(i);
    }
    for (int i = 0; i < 10; i++) {
        System.out.println(i);
    }
}

Is there any difference between i++ and ++i? If yes, which(is) would be(m)?

4 answers

17


There is a slight difference between the two. The i++ ("post-increment") returns the initial value of i and the ++i ("preincrement") returns the incremented value of i.

Example:

int i = 0;
int j = 0;

int a = i++; // a = 0, i = 1
int b = ++j; // b = 1, j = 1

Ideone: https://ideone.com/TPk7Qs

This behavior is equal in several languages, for example in PHP and Javascript, and also works with decreasing.

  • 2

    Just to complement: put the ++ before variable has the operation name of preincrement and put the ++ afterward variable has the operation name of post-increment. Also valid for subtraction operations: --i (pre-decrement) and i-- (post decrement).

  • 1

    @Igorventurelli thanks! I joined the reply to get more complete.

  • Related: https://msdn.microsoft.com/pt-br/library/e1e3921c.aspx

  • 1

    Curiosity: these operators as ++ were born in the language B, precursor of C, so they appear in most derivatives of C.

6

For the example shown in the loop for both the preincrement:

for (int i = 0; i < 10; ++i) {

Like the post increment:

for (int i = 0; i < 10; i++) {

They end up being the same, resulting only in a difference in writing style.

The difference only occurs when we use the variable that is being incremented at the moment it is incremented.

Trying to show an example different from the other answers, consider an array and a variable that indicates the position you want to change:

int[] arr = new int[10];
int pos = 0;

Now making:

arr[pos++] = 10;

Will make the position 0 has been 10 and the pos keep 1 after the instruction is finished, once the increment is done after.

Whereas:

arr[++pos] = 10;

Will first increase the pos and put the 10 already in position 1.

3

It is the idea of post and pre-increment, the same happens in the case of -- ... i++ is the post-increment or i will only be incremented after the line of code is executed, is ++i is the pre-increment in case i will be incremented before the line of code is fully executed

2

I did it once at Solo Learn, and people liked the simplicity:

<?php

    # Antes
    $a = 5;
    $b = $a++;
    echo "b = ".$b; // b = 5

    echo "<hr>";

    # Depois
    $x = 5;
    $y = ++$x;
    echo "y = ".$y; // y = 6

?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.