Win a copy of Bad Programming Practices 101 (e-book) this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Do you use ++i or i++ in for loops?  RSS feed

 
Saloon Keeper
Posts: 1691
68
Android Chrome IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These two lines are effectively the same:

I know this, however I usually use option A. It just seems more correct to me.
I'm sure that everyone has their own little quirks about the code they write, which don't really change the ending result.

How do you like to increment your simple for loop counter?
 
Author and ninkuma
Marshal
Posts: 66727
167
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Option A because it's the convention. That is, when I used that type of for statement. 99% of the time I end up using the non-indexed form of for.
 
Ranch Hand
Posts: 207
3
Java MySQL Database Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think Option B
 
Sheriff
Posts: 23586
48
Eclipse IDE Firefox Browser MySQL Database
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Bear Bibeault wrote:Option A because it's the convention.



Absolutely. If I was given code and it used Option B, I would have to stop and think for a few seconds about why Option A wasn't used. And when I'm looking at somebody else's code, there's enough real things to think about. Don't make me think about irrelevant trivia!
 
Marshal
Posts: 5802
401
BSD
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

O Shea wrote:I think Option B


Any reasoning?
 
O Shea
Ranch Hand
Posts: 207
3
Java MySQL Database Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Liutauras Vilda wrote:Any reasoning?


Yes, just for fun to try something different.
 
Saloon Keeper
Posts: 8980
168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I prefer to use option A because I'm used to it and it somehow looks more visually pleasing to me. However, I will use option B if that's consistent with the rest of the project.
 
Marshal
Posts: 59403
187
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

O Shea wrote:[. . . to try something different.

As long as you don't expect anybody else to read it, that is. There are reasons for following conventions which Paul C has already told you about.
 
Sheriff
Posts: 12078
197
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Convention is my main consideration in using post-increment. However, I do seem to recall reading somewhere that in JavaScript, the pre-increment can result in slightly better performance. Don't use this as an excuse to do premature optimization though. Code for clarity first, then optimize if there are problems. And always base optimization decisions on your own quantified performance testing results, not on gut feeling or word of mouth.
 
Bartender
Posts: 19553
90
Android Eclipse IDE Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first form is more commonly preferred, but aside from that the two statements are only identical in effect for this particular case. One is a post-increment, the other is a pre-increment.

Consider the following:That will assign q[0] to z[0], q[2] to z[1], q[4] to z[2]...

Contrast with:

That will assign q[2] to z[0], q[4] to z[1], q[6] to z[2]...

Or, more commonly, a countdown loop:
That would count 5, 4, 3, 2, 1.

Versus:
Which would be 4, 3, 2, 1.
 
Sheriff
Posts: 4966
136
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Tim Holloway wrote:


I believe that should be and also the other for loop.
 
Tim Holloway
Bartender
Posts: 19553
90
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Knute Snortum wrote:

Tim Holloway wrote:


I believe that should be and also the other for loop.



I spent so much time trying not to screw up my calculations, I missed the fact that I got the order wrong. Typical.
 
Paul Clapham
Sheriff
Posts: 23586
48
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Tim Holloway wrote:I spent so much time trying not to screw up my calculations...



This is why I (personally) try to avoid using either i++ or ++i. As I said, I'll use it in the canonical for-loop because that's a well-known idiom, but otherwise I'll avoid it. Even to the point of writing



instead. Fortunately I never have to write code like Tim's examples, and even if I did I wouldn't be looking for code like Tim's. No doubt people brought up on C coding would have no problem at all with that code, but I wasn't ever a C programmer.
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i would use option A because it would use the I value for that loop and then it would add another i when it is done making it repeat again.
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You would use i++, it would run the loop and then increment i, as to not mess up the loop.
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You use i++ at  the end my dude. Hope this helped!
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a for loop, whether you pre-increment or post-increment doesn't matter. It is up to your preference, and i prefer i++ by convention.
In a while loop, however, this is an important distinction.

In this case, you must chose based on the logic of your program (whether you want to increment before or after the comparison).
 
Junilu Lacar
Sheriff
Posts: 12078
197
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would avoid pre-increment and post-increment operators in a while-loop condition as much as possible. It's not as idiomatic as it is with the for-loop so most people will have to pause and read it carefully to make sure they understand exactly when the while-loop terminates and what the value of the variable will be after the loop.
 
Campbell Ritchie
Marshal
Posts: 59403
187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Apart from that code being error‑prone, your explanation isn't quite right. In the case of
while (i++ < 0) ...
the increment to i is carried out before the comparison, but it is not visible. The value of i is hidden because the value of the whole expression i++ is equal to the old value of i. Yes, both for ++i and i++ there are two values. Since the new value of i and the value of ++i are the same, that doesn't seem to cause any confusion and people never even realise there is an issue in the first place.
 
Greenhorn
Posts: 5
  • Likes 1 Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the difference between ++i and i++ is whether one is added to i before the statement is used in the case of ++i, or after the statement is done with i++

here is some example code with comments to better define whats happening:

 
Campbell Ritchie
Marshal
Posts: 59403
187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Daniel Bernardy wrote:the difference between ++i and i++ is whether one is added to i before the statement is used . . . or after the statement is done . . .
        //returns 0 because it adds one to i after the print line is executed
. . .

I am afraid that is incorrect. The instruction inside the () has to be completed before the print instruction is executed, but you cannot see the value of i. The value of the whole expression i++ is equal to the old value of i. The details are in the Java® Language Specification (=JLS):-

That JLS Section wrote:The value of the postfix increment expression is the value of the variable before the new value is stored.

The new value of i becomes visible later whenever you use i again.

Postfix expressions are notorious for confusing beginners.
 
Junilu Lacar
Sheriff
Posts: 12078
197
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To see what Campbell is talking about, try this:
 
Greenhorn
Posts: 14
1
Chrome IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I was a C++ programmer, you could get a little performance increase by using ++i rather than i++.

These days though, I'm not sure it makes any difference and the convention in Java is to use i++.

Personally I don't use for loops much these days as I tend to use the Java 8 Stream API which is more concise and reads a bit better.
 
Campbell Ritchie
Marshal
Posts: 59403
187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some people say there is a performance enhancement in Java® too if you use i++, but what is one clock cycle between friends?
 
Baz Edwards
Greenhorn
Posts: 14
1
Chrome IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Some people say there is a performance enhancement in Java® too if you use i++, but what is one clock cycle between friends?



Well it doesn't matter so much in Java, but at the time when I was writing C++, it did matter, a lot of my applications were performance critical.
 
Campbell Ritchie
Marshal
Posts: 59403
187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. I seem to have got my previous post wring; I meant to say they say ++i is faster. Sorry.
 
Baz Edwards
Greenhorn
Posts: 14
1
Chrome IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Thank you. I seem to have got my previous post wring; I meant to say they say ++i is faster. Sorry.


I knew what you meant mate, no worries
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both work its just convention wise "i++" is more acceptable. Also, depending on your code using "++i" could return an error depending on what you are using your loop for.
 
Liutauras Vilda
Marshal
Posts: 5802
401
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Mickey Loveless wrote:Also, depending on your code using "++i" could return an error depending on what you are using your loop for.


Please explain what you mean here. Maybe an example of such error case?
 
Junilu Lacar
Sheriff
Posts: 12078
197
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Mickey Loveless wrote:Both work its just convention wise "i++" is more acceptable. Also, depending on your code using "++i" could return an error depending on what you are using your loop for.


Hmmm... I agree with Liutauras on this. It's not good to give FUD-based advice (Fear, Uncertainty, and Doubt) and "could return an error depending..." sure sounds like FUD. Please give a concrete example or cite your source(s).
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would prefer option B (++i) simply because it makes sure the value is where it should be when running the loop, although personally I don't think it matters when using a for loop.
 
Junilu Lacar
Sheriff
Posts: 12078
197
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Andy Frels wrote:I would prefer option B (++i) simply because it makes sure the value is where it should be when running the loop, although personally I don't think it matters when using a for loop.


In professional work, convention takes precedence over personal preference. The convention for Java for-loop iteration increment clauses like the one OP asked about is to use post-increment:

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

That is the standard idiom and you should always try to write idiomatic code -- it's easier to read because it's what most people expect to see.

There is absolutely no functional difference between ++i and i++ as the iteration increment clause.

EDIT: That part of the for-loop header is actually called the "increment clause."
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I++, because everything will have to be evaluated before you add on I.
 
Paul Clapham
Sheriff
Posts: 23586
48
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could you be more specific about what's included in the "everything" which you say will have to be evaluated?
 
Junilu Lacar
Sheriff
Posts: 12078
197
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Roger Williamson wrote:I++, because everything will have to be evaluated before you add on I.


Again, there is absolutely NO functional difference between these two as far as controlling the loop iteration and increment is concerned:

When you have for-loop code in this form, the former is preferable because it is the conventional way to write it and it's what most people expect to see.
 
Campbell Ritchie
Marshal
Posts: 59403
187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Roger Williamson wrote:. . . everything will have to be evaluated before you add on I.

I am afraid that isn't correct. As Junilu has hinted, the increment clause of the for statement header is executed as if it were a separate statement. The loop is executed rather like this:-
  • 1: Initialise loop variable.
  • 2: Test whether continuation condition is true. If not, loop terminates.
  • 3: Execute body of loop.
  • 4: Execute increment clause as a separate action.
  • 5: Go to stage 2.
  • There is no difference in the results of using i++ and ++i as statements on their own. The difference is only seen if they are used as part of a larger statement. Yes, it is possible to write larger statements there. That way lies confusion.
    Note that stage 2 doesn't have to return true in all circumstances; if it returns false on the first try, the loop will never start.
     
    Junilu Lacar
    Sheriff
    Posts: 12078
    197
    Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:As Junilu has hinted


    I was actually going for emphatically noted...
     
    Ranch Hand
    Posts: 1153
    9
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Junilu Lacar wrote:
    Again, there is absolutely NO functional difference between these two as far as controlling the loop iteration and increment is concerned:

    When you have for-loop code in this form, the former is preferable because it is the conventional way to write it and it's what most people expect to see.



    Agreed 100%.
    - There is no functional or performance difference in any modern implementation of any language that uses those idioms, including of course Java.
    - It is far more important to use the more common convention than to follow meaningless personal preference.

    However, I will say I'm a little sad that i++ gained more of a foothold than ++i.  If I could go back in time, I'd advocate for ++i more.  Why?
    - It's easier to read "++i" and say "increment i".  The increment operator and the variable are in the correct order.
    - In the few cases where the value of the expression is used, it's more likely (in my experience) that you want the new, incremented value of i instead of the old value.

    https://xkcd.com/567/
     
    Junilu Lacar
    Sheriff
    Posts: 12078
    197
    Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Ryan McGuire wrote:
    - In the few cases where the value of the expression is used, it's more likely (in my experience) that you want the new, incremented value of i instead of the old value.


    Not to be argumentative but let's examine your statement carefully.

    The JLS defines the third clause in a basic for-loop statement as the "ForUpdate" which is further defined as a "StatementExpressionList" which is defined as StatementExpression {, StatementExpression} - See https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.1

    Following the link for StatementExpression, we see that it's defined as one of the following:
    Assignment
    PreIncrementExpression
    PreDecrementExpression
    PostIncrementExpression
    PostDecrementExpression
    MethodInvocation
    ClassInstanceCreationExpression

    Of these, we can ignore the PreIncrement, PostIncrement, PreDecrement, and PostDecrement because these are standalone and as we've already emphatically noted a few times, has no functional differences. So we're left with Assignment, Method Invocation, and surprisingly (I didn't realize this before today), ClassInstanceCreationExpression to reconcile with your statement that "in a few cases where the expression is used, ... it is more likely that you'll want the new, incremented value of i instead of the old value."

    I'd like to see if there are any good examples where a ForUpdate that is one of Assignment, MethodInvocation, or ClassInstanceCreationExpression where using ++i as part of it is preferable. That is, you have a choice to use either ++i or i++ but the former is better for some reason other than correctness.

    (continued...)
     
    If you believe you can tell me what to think, I believe I can tell you where to go. Go read this tiny ad!
    Why should you try IntelliJ IDEA ?
    https://coderanch.com/wiki/696337/IntelliJ-IDEA
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!