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

10

I found a piece of code in an application that I'm giving continuity that I had not seen yet (or had never noticed). I casually always used i++ in a loop of repetition, for example, however in this section it was ++i and I did not notice any difference in the result. Here is 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 so, which one would it be?

    
asked by anonymous 04.10.2017 / 08:10

4 answers

15

There is a slight difference between the two. The i++ ("post increment") returns the initial value of i and the ++i ( "pre increment" ) 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: link

This behavior is the same in several languages, for example in PHP and JavaScript, and also works with decrement.

    
04.10.2017 / 08:19
6

For the example shown in the loop% re% loop both the pre increment:

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

As the post-increment:

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

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

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

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

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

Now doing:

arr[pos++] = 10;

It will cause the for position to have 0 and 10 to get pos after the statement finishes, since the increment is done later.

While:

arr[++pos] = 10;

You will first increase 1 and put pos already in position 10 .

    
04.10.2017 / 11:29
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, it is in ++ i is the pre-increment in case i will be incremented before the code line is executed completely

    
04.10.2017 / 11:14
2

Once I did this in Solo Learn, and the staff enjoyed 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

?>
    
04.10.2017 / 12:26