views:

350

answers:

25

Why does this

 int x = 2;
    for (int y =2; y>0;y--){
        System.out.println(x + " "+ y + " ");
        x++;
    }

prints the same as this?

 int x = 2;
        for (int y =2; y>0;--y){
            System.out.println(x + " "+ y + " ");
            x++;
        }

As far, as I understand a post-increment is first used "as it is" then incremented. Are pre-increment is first added and then used. Why this doesn't apply to the body of a for loop?

+5  A: 

Because that statement is just on it's own. The order of the increment doesn't matter there.

Noon Silk
+3  A: 

Because nothing in your examples is using the value returned from the pre- or post-increments. Try wrapping a System.out.println() around the ++x and x++ to see the difference.

Alan Krueger
+25  A: 

The loop is equivalent to:

int x = 2;
int y = 2;
while (y > 0)
{
   System.out.println(x + " "+ y + " ");
   x++;
   y--; // or --y;
}

As you can see from reading that code, it doesn't matter whether you use the post or pre decrement operator in the third section of the for loop.

More generally, any for loop of the form:

for (ForInit ; Expression ; ForUpdate)
    forLoopBody();

is exactly equivalent to the while loop:

{
    ForInit;
    while (Expression) {
        forLoopBody();
        ForUpdate;
    }
}

The for loop is more compact, and thus easier to parse for such a common idiom.

Paul Wagland
+1  A: 

Because the value of y is calculated in for statement and the value of x is calculated in its own line, but in the System.out.println they are only referenced.

If you decremented inside System.out.println, you would get different result.

System.out.println(y--);
System.out.println(--y);
Superfilin
+2  A: 

From the Java Language Specification chapter on for loops:

BasicForStatement:

    for ( ForInit ; Expression ; ForUpdate ) Statement

... if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. ... If the ForUpdate part is not present, no action is taken.

(highlight is mine).

ChssPly76
A: 

The increment is executed as an independent statement. So

y--;

and

--y;

are equivalent to each other, and both equivalent to

y = y - 1;

Ken Paul
A: 

Because this:

int x = 2;
for (int y =2; y>0; y--){
    System.out.println(x + " "+ y + " ");
    x++;
}

Effectively gets translated by the compiler to this:

int x = 2;
int y = 2
while (y > 0){
    System.out.println(x + " "+ y + " ");
    x++;
    y--;
}

As you see, using y-- or --y doesn't result in any difference. It would make a difference if you wrote your loop like this, though:

int x = 2;
for (int y = 3; --y > 0;){
    System.out.println(x + " "+ y + " ");
    x++;
}

This would yield the same result as your two variants of the loop, but changing from --y to y-- here would break your program.

gustafc
+1  A: 

There are a lot of good answers here, but in case this helps:

Think of y-- and --y as expressions with side effects, or a statement followed by an expression. y-- is like this (think of these examples as pseudo-assembly):

decrement y
return y

and --y does this:

store y into t
decrement y
load t
return t

In your loop example, you are throwing away the returned value either way, and relying on the side effect only (the loop check happens AFTER the decrement statement is executed; it does not receive/check the value returned by the decrement).

danben
A: 

It's a matter of taste. They do the same things.

If you look at code of java classes you'll see there for-loops with post-increment.

Roman
They do the same thing *if you're not using the result of the expression*.
Michael Myers
@mmyers: you're right. But I've never seen the code which do that (of course, it doesn't mean that *that* code doesn't exist).
Roman
+11  A: 

There's no difference in terms of performance, if that's your concern. It can only be used wrongly (and thus sensitive to errors) when you use it during the increment.

Consider:

for (int i = 0; i < 3;)
   System.out.print(++i + ".."); //prints 1..2..3


for (int i = 0; i < 3;)
   System.out.print(i++ + ".."); //prints 0..1..2

or

for (int i = 0; i++ < 3;)
   System.out.print(i + ".."); //prints 1..2..3


for (int i = 0; ++i < 3;)
   System.out.print(i + ".."); //prints 1..2

Interesting detail is however that the normal idiom is to use i++ in the increment expression of the for statement and that the Java compiler will compile it as if ++i is used.

BalusC
However, how he used them there isn't a difference, because the `++i` or `i++` operation is done alone.
R. Bemrose
The post-increment operator will need to keep the old value available to be used after the incrementation. So your second example needs to hold `0`, increment `i`, remember `0` for the String concatenation.
Ben S
+1. Never before I thought about for-loop as about 3 lines of usual code.
Roman
A: 

in your case, it's the same, no difference at all.

manuel
A: 

The check is done before the increment argument is evaluated. The 'increment' operation is done at the end of the loop, even though it's declared at the beginning.

Kylar
+2  A: 

Those two cases are equivalent because the value of i is compared after the increment statement is done. However, if you did

if (i++ < 3) 

versus

if (++i < 3)

you'd have to worry about the order of things.

And if you did

i = ++i + i++;

then you're just nuts.

Paul Tomblin
...nuts like a fox!
Jim Kiley
@Jim - with rabies.
Paul Tomblin
+5  A: 

This loop is the same as this while loop:

int i = 0;
while(i < 5)
{
     // LOOP
     i++; // Or ++i
}

So yes, it has to be the same.

Cedric H.
or `while(i++ < 5)`
rmx
@rmx: but not `while(++i < 5)` and thats the point
Progman
@Progman: Wouldn't `while(i++ < 5){...}` be the equivalent of `while(i < 5){i += 1;...}` rather than the `for`-equivalent `while(i < 5){...;i += 1;}`?
Alan
A: 

You are right. The difference can be seen in this case:

for(int i = 0; i < 5; )
       {
            System.out.println("i is : " + ++i);           
       }
killer_PL
+16  A: 

To visualize these things, expand the for loop to a while loop:

for (int i = 0; i < 5; ++i)
    do_stuff(i);

Expands to:

int i = 0;
while (i < 5) {
    do_stuff(i);
    ++i;
}

Whether you do post-increment or pre-increment on the loop counter doesn't matter, because the result of the increment expression (either the value before or after the increment) isn't used within the same statement.

tdammers
A: 

Yes it does it sequentially. Intialisation, then evaluation condition and if true then executing the body and then incrementing.

Prefix and Postfix difference will be noticable only when you do an Assignment operation with the Increment/Decrement.

+12  A: 

++i and i++ makes a difference when used in combination with the assignment operator such as int num = i++ and int num = ++i or other expressions. In above FOR loop, there is only incrementing condition since it is not used in combination with any other expression, it does not make any difference. In this case it will only mean i = i + 1.

Sachin Shanbhag
13 upvotes? But it's wrong! Not _only_ when used with assignment operator: always the result of the expression is to be used (e.g. arithmetic comparisons and method parameters too).
fortran
@fortran: The question asks about difference between using i++ or ++i in FOR loop. So in context of FOR loop, both mean the same. Can you explain a bit more if my answer is wrong in this context?
Sachin Shanbhag
`for(int i = 0; i < 10; doSomething(i++))` or `for(i = -1; ++i < 10;)` really make a difference if used with pre or post increment... So yes, your assertion, even if it's completely in the context of a `for` loop (and read it again to check that you aren't specifying the context in the first sentence) is wrong.
fortran
@fortran: have edited my answer, will this be fine now in the current question context?
Sachin Shanbhag
A: 

There is no differences because every part of the for "arguments" are separated statements.

And an interesting thing is that the compiler can decide to replace simple post-incrementations by pre-incrementations and this won't change a thing to the code.

Colin Hebert
I assume that the (smart) compiler will choose neither post nor pre-incrementation, just add 1 to the variable (`i += 1`, INC bytecode) since the result is not used in the statement.
Carlos Heuberger
To be precise the ByteCode will be `iinc` and it will replace `i++`, `++i` and `i += 1`.I just wanted to say that the compiler will extract the `++i`, `i++` operation from the statement in every case, to change it in the `simple iinc` placed before or after the original statement.
Colin Hebert
+1  A: 

Try this example:

int i = 6;
System.out.println(i++);
System.out.println(i);

i = 10;
System.out.println(++i);
System.out.println(i);

You should be able to work out what it does from this.

Noel M
+1  A: 

If the for loop used the result of the expression i++ or ++i for something, then it would be true, but that's not the case, it's there just because its side effect.

That's why you can also put a void method there, not just a numeric expression.

fortran
A: 

They DON'T behave the same. The construct with i++ is slightly slower than the one with ++i because the former involves returning both the old and the new values of i. On the other side, the latter only returns the old value of i.

Then, probably the compiler does a little magic and changes any isolated i++ into a ++i for performance reasons, but in terms of raw algorithm they are not strictly the same.

saverio
Are you sure the performance argument is valid in the `for` loops case? My guess would be that most compilers are intelligent enough to change i++ for ++i.
Pin
They DO *behave* the same. They may(?) have different performance characteristics, but their behaviour is the same.
bruceboughton
Pin: As I and many others say in the answer, probably the compiler is able to swap in the prefix increment in place of the postfix one.
saverio
the compiler will change it to a simple `INC` byte code, equivalent to `i += 1`.
Carlos Heuberger
A: 

There's many similar posts at Stackoverflow:

However, it seems your question is more generic because it's not specific to any language or compiler. Most of the above questions deal with a specific language/compiler.

Here's a rundown:

  • if we are talking about C/C++/Java (probably C# too) and a modern compiler:
    • if i is an integer (const int, int, etc.):
      • then the compiler will basically replace i++ with ++i, because they are semantically identical and so it doesn't change the output. this can be verified by checking the generated code / bytecode (for Java, I use the jclasslib bytecode viewer).
    • else:
  • else:
    • all bets are off, because the compiler cannot guarantee that they are semantically identical, so it does not try to optimize.

So if you have a class in C++ that overrides the postfix and prefix operators (like std::iterator), this optimization is rarely, if ever, done.

In summary:

  • Mean what you say, and say what you mean. For the increment part of for loops, you almost always want the prefix version (i.e., ++i).
  • The compiler switcheroo between ++i and i++ can't always be done, but it'll try to do it for you if it can.
The Alchemist
+1  A: 

The output is the same because the 'increment' item in the 'for (initial; comparison; increment)' doesn't use the result of the statement, it just relies on the side-effect of the statement, which in this case is incrementing 'i', which is the same in both cases.

EJP
A: 

in a loop, first initialization, then condition checking, then execution, after that increment/decrement. so pre/post increment/decrement does not affect the program code.

alfesani