What is the difference between i++ & ++i in a for loop? [duplicate]
Asked Answered
P

7

26

I've just started learning Java and now I'm into for loop statements. I don't understand how ++i and i++ works in a for-loop.

How do they work in mathematics operations like addition and subtraction?

Paste answered 23/2, 2010 at 2:13 Comment(3)
Many existing instances. Short answer: for native types nothing. #484962 #1941891 and many others taken from stackoverflow.com/search?q=i%2B%2B+%2B%2BiPrecondemn
related: #1756515St
++i should be more efficient in theory since i++ simply a ++i and a copy ( to save the earlier value ) But i guess JVM will optimize the latter in a for loop (atleast any compiler would do...) -> no differenceRichma
U
55

They both increment the number. ++i is equivalent to i = i + 1.

i++ and ++i are very similar but not exactly the same. Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated.

int i = 3;
int a = i++; // a = 3, i = 4
int b = ++a; // b = 4, a = 4
Unrobe answered 23/2, 2010 at 2:16 Comment(2)
To answer the actual question, however, they're essentially identical within the context of typical for loop usage.Northwestwards
Point of pedantry: i = i + 1 is an expression with a value one more than the initial value of i, which would make it more like ++i.Mechanics
I
44

Here's a sample class:

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

If I disassemble this class using javap.exe I get this:

Compiled from "Increment.java"
public class Increment extends java.lang.Object{
public Increment();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_0
   1:   istore_1
   2:   iload_1
   3:   aload_0
   4:   arraylength
   5:   if_icmpge       23
   8:   getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   11:  aload_0
   12:  iload_1
   13:  aaload
   14:  invokevirtual   #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   17:  iinc    1, 1
   20:  goto    2
   23:  return

}

If I change the loop so it uses i++ and disassemble again I get this:

Compiled from "Increment.java"
public class Increment extends java.lang.Object{
public Increment();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_0
   1:   istore_1
   2:   iload_1
   3:   aload_0
   4:   arraylength
   5:   if_icmpge       23
   8:   getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   11:  aload_0
   12:  iload_1
   13:  aaload
   14:  invokevirtual   #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   17:  iinc    1, 1
   20:  goto    2
   23:  return

}

When I compare the two, TextPad tells me that the two are identical.

What this says is that from the point of view of the generated byte code there's no difference in a loop. In other contexts there is a difference between ++i and i++, but not for loops.

Interlocutory answered 23/2, 2010 at 2:36 Comment(4)
+1 for going the extra mile.Rustler
It's not the loop that's doing it, it's the fact that it's not in a larger expression context. If your loop-end expression was more complicated, it might very well make a difference.Irreversible
I'll add more to the loop example and try again to see.Interlocutory
Absolute +1 for this answer! ... Although it can makes difference in situation like: "for (int i = 0, int j = 0; i < args.length; j += ++i)" vs. "for (int i = 0, int j = 0; i < args.length; j += i++)"Shanta
P
20

Both of them increase the variable i by one. It's like saying i = i + 1. The difference is subtle. If you're using it in a loop like this, there's no difference:

for (int i = 0; i < 100; i++) {
}

for (int i = 0; i < 100; ++i) {
}

If you want to know the difference, look at this example:

int a = 0;
int b = a++; // b = 0; a = 1

a = 0;
b = ++a: // b = 1; a = 1

The idea is that ++a increments a and returns that value, while a++ returns a's value and then increments a.

Panjabi answered 23/2, 2010 at 2:18 Comment(0)
B
7

The way for loop is processed is as follows

1 First, initialization is performed (i=0)

2 the check is performed (i < n)

3 the code in the loop is executed.

4 the value is incremented

5 Repeat steps 2 - 4

This is the reason why, there is no difference between i++ and ++i in the for loop which has been used.

Bainter answered 23/2, 2010 at 3:18 Comment(1)
This was the answer that I was looking for. Thank you!Labourite
I
5

The difference is that the post-increment operator i++ returns i as it was before incrementing, and the pre-increment operator ++i returns i as it is after incrementing. If you're asking about a typical for loop:

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

or

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

They're exactly the same, since you're not using i++ or ++i as a part of a larger expression.

Irreversible answered 23/2, 2010 at 2:17 Comment(0)
I
3

Both i++ and ++i are short-hand for i = i + 1.

In addition to changing the value of i, they also return the value of i, either before adding one (i++) or after adding one (++i).

In a loop the third component is a piece of code that is executed after each iteration.

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

The value of that part is not used, so the above is just the same as

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

or

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

Where it makes a difference (between i++ and ++i )is in these cases

while(i++ < 10)

for (int i=0; i++ < 10; )
Inextirpable answered 23/2, 2010 at 2:16 Comment(1)
See TomH's pedantry in David's answer, i=i+1 is identical to ++i, not i++ :-)Rustler
A
0

JLS§14.14.1, The basic for Statement, makes it clear that the ForUpdate expression(s) are evaluated and the value(s) are discarded. The effect is to make the two forms identical in the context of a for statement.

Aedile answered 23/2, 2010 at 4:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.