Reputation: 2545
I mean:
for (int i = 0; i < 10; i++)
System.out.println(i);
and
for (int i = 0; i < 10; ++i)
System.out.println(i);
Will yield the same results. Is ++i
not evaluated at all till the first loop completes?
Upvotes: 1
Views: 1818
Reputation: 60414
Because your for
loop is equivalent to this:
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
The post- or pre-increment operation is evaluated at the end (and its return value thrown away), before the condition is checked on the next iteration.
They would be quite different if the return value were used. The following code is equivalent to the loop above:
int i = 0;
while (i < 10) {
System.out.println(i);
i = ++i; // pre
}
...but this code creates an infinite loop (i
is never incremented):
int i = 0;
while (i < 10) {
System.out.println(i);
i = i++; // post
}
Warning: These last two examples are Java-specific. The behavior in C and C++ is undefined and the two may very well be equal on your compiler.
Upvotes: 5
Reputation: 17444
Because the language specification says so:
If the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded.
Upvotes: 0
Reputation: 601
Using i++ this means that i will be incremented immediately after use and ++i means i will be incremented just before use.
i = 1;
y = i++;
y = 1, i = 2
i = 1;
y = ++i;
y = 2, i = 2
In the case of a for loop, the increment operator is called entirely independent of when it is evaluated, so think of it as a line at the end of the loop by itself either being
i++; OR ++i;
It is incremented and then evaluated against your center condition.
Upvotes: 1
Reputation: 10177
There is just a subtle difference in ++i
and i++
:
i++
first returns the value of i and then increments it by one.++i
first increments value of i and then returns the value.Since the return value is not used for anything, it doesn't matter in this case.
Upvotes: 2
Reputation: 27233
The ++i
and i++
differ in what they return (their side-effects are the same: increasing i
by one). The loop for(start; condition; step)
has three expressions in it, but it only looks at the value returned by the condition
. While it does execute step
every iteration it just drops the result, i.e. step
's side-effect is all that matters.
Upvotes: 1
Reputation: 4324
You are correct. i++ and ++i yields the same results because it is evaluated in the end of the iteration and not used.
Upvotes: 1
Reputation: 81349
Whether you use i++
or ++i
is the same, since the return value is unused. The expression is evaluated after going through the loop body, and before evaluating the continuation condition. Note that they are two separate expressions. That is, they are different from:
i++ < 10
++i < 10
which would yield different results for i = 9
.
Upvotes: 1