Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Sheriff
Posts: 11744
191
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And it's not that I doubt your experience but I have to question what you said and ask for a concrete example because your statement does not resonate with my own experience with for loops and pre/post increment operators, at least not with anything that stands out in my aging memory.
 
Marshal
Posts: 5589
383
BSD
  • 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.


@Junilu

What Ryan had in his head, I think were situations like, which have nothing to do with for loops:
Let's ignore the fact it is a poor practice. But I think that was idea he was trying to express about his experience

Of course Ryan is the best source to either confirm or negate that.
 
Junilu Lacar
Sheriff
Posts: 11744
191
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's look at Assignment first.

Let's say we define a for-loop like this:

Where SENTINEL is a constant value which, if j is equal to it, would cause the for-loop to terminate. Now, since the ++i is involved in an expression whose value is assigned to j and j is part of the loop termination expression, then obviously, you have no choice but to use ++i or i++, whichever is correct for the particular algorithm involved. That is, either the code above is correct, or this is correct:

They cannot both be correct because the expressions result in different behavior of the for-loop. So in this case, there is no "preferring" one over the other since you can only use the form that results in the correct logic. 

I don't know if this is representative of all cases where the ForUpdate is an Assignment but I'm hard-pressed to think of another example where you actually have a choice other than to use the form that will give you the correct results.
 
Liutauras Vilda
Marshal
Posts: 5589
383
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Ryan McGuire wrote:If I could go back in time, I'd advocate for ++i more.  Why?
- It's easier to read "++i" and say "increment i".


I like this thought.

And again, Ryan I think doesn't relate that directly with for-loop, but rather in general to have this as idiomatic way. While I think majority of tutorials, which could be found on internet, in case of singular increment statement within a line would probably contain i++ rather than ++i.
 
Junilu Lacar
Sheriff
Posts: 11744
191
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For both the MethodInvocation and the ClassInstanceCreationExpression, I think the same reasoning applies.  You don't actually have a choice between using ++i or i++ as part of a method invocation or a class instance creation expression since they will not be functionally equivalent. That is,

and

In both these cases, one is most likely the correct thing to do while the other is not. So again, there's really no "preference" here because you can only choose to do the right thing.
 
Junilu Lacar
Sheriff
Posts: 11744
191
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Liutauras Vilda wrote:

Ryan McGuire wrote:If I could go back in time, I'd advocate for ++i more.  Why?
- It's easier to read "++i" and say "increment i".


I like this thought.


I have to admit, I'm all about writing code that resonates with me when I read it out loud. If things had gone differently, this would absolutely be very natural to read that way.
 
Liutauras Vilda
Marshal
Posts: 5589
383
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[edit] added quote not to confuse conversation

Junilu Lacar wrote:In both these cases, one is most likely the correct thing to do while the other is not. So again, there's really no "preference" here because you can only choose to do the right thing.


Indeed. But probably Java easily could live only with one existing increment. As we see for many people that causes confusion. On the other hand, most likely only for first semester students. Having both gives more flexibility and I could easily find at work cases of both usages. So these have use.
 
Junilu Lacar
Sheriff
Posts: 11744
191
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Liutauras Vilda wrote:
What Ryan had in his head, I think were situations like, which have nothing to do with for loops:
Let's ignore the fact it is a poor practice.


The thing is, when you're talking about "preference" you can't ignore correctness or poor practice. Who "prefers" writing code that reflects poor practice? Nobody, right? At least I hope that's the case.

Given your example, I'd prefer to write this:
or

or some variation of the above, using two separate statements. The one-liner with the preincrement operator is just too cute for its own good. But then again, that's just my preference. 

BTW, this isn't relevant to the for-loop ForUpdate clause discussion so I'm not sure why we even digressed down this path.
 
Junilu Lacar
Sheriff
Posts: 11744
191
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Liutauras Vilda wrote:But probably Java easily could live only with one existing increment.


The creators of the Go Language were likely thinking along the same lines. https://golang.org/doc/faq#inc_dec
 
Liutauras Vilda
Marshal
Posts: 5589
383
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:Given your example, I'd prefer to write this:
or
...


We have a match here. Or more exactly, I took those lessons from you and others who advocate clean and clear code over some other less important factors which usually to quite a few look other way round.
 
Marshal
Posts: 58319
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
t means the daily interest increases day by day and the penalty increases by an increasing amount. Is that the correct formula?
Having both i++ and ++i works nicely for array indices. But not for anything else.

I think Java® was handicapped because Gosling was trying to follow the syntax of C++ too closely. In C they use both i++ and ++i because they still think it is 1972 and every byte of memory used costs a significant amount, so they like to write code as short as possible. That necessitates both kinds of unary ++ (and --) operator. In the early days that worked, but now people go straight to Java® and the two operators cause confusion. As Liutauras says, usually only in the early days.
 
Campbell Ritchie
Marshal
Posts: 58319
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:. . . Let's say we define a for-loop like this:. . .

There are all sorts of things you can do. It is for example possible to open the door in a moving car and fling some rubbish out. What a dreadful thing to do, throwing rubbish all over my streets. I am quite sure you would never throw rubbish on my streets, Junilu, nor would you write that sort of loop in real life.
Yes, you can define a loop like that, but as other people have said, what horrible code.  Why not go all the way and put a semicolon at the end of line 1? There is no need to have the increment in the heading at all. That increment can go in the loop body, as multiple statements, but it might be worthwhile writing a comment to explain why there ain't no increment part in the heading.
 
Liutauras Vilda
Marshal
Posts: 5589
383
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Liutauras Vilda wrote:it means the daily interest increases day by day and the penalty increases by an increasing amount. Is that the correct formula?


It was a hypothetical scenario, so I don't remember what I was thinking at that time when authored that formula, but looks some kind of ok, nevermind (it was just to demonstrate ++), Junilu is right, we moved from the main topic with formulae - I think it was me actually. Sorry.
 
Junilu Lacar
Sheriff
Posts: 11744
191
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:

Junilu Lacar wrote:. . . Let's say we define a for-loop like this:. . .

There are all sorts of things you can do. ...
Yes, you can define a loop like that, but as other people have said, what horrible code.


I was trying to reason about using a pre- or post-increment expression as part of an assignment as a valid scenario where one might prefer one form over another. The merits of using pre or post increment in an assignment, or lack thereof, was not part of that reasoning.

That reply you quoted was part of the long series of replies in response to Ryan's one assertion. I was just trying to find a way to reconcile his claim that in his experience, a pre-increment expression can be preferable to a post increment expression in some cases. That is not something that meshes with my own experience so I was trying to eliminate possibilities. You might want to go back a few replies more to get more context.
 
Junilu Lacar
Sheriff
Posts: 11744
191
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course I did reason that you would hardly prefer doing something that is considered poor form or practice when I responded to Liutauras earlier, so I could have eliminated The Assignment form of a ForUpdate immediately. You never prefer to use a preincrement or post increment expression as part of an assignment unless maybe it's the only term on the right hand side. But then again in that case it wouldn't really be a preference because only one form can be correct in any given context.

What if the pre/post increment expression was used in the left hand side of an Assignment ForUpdate... ? Hmmm... Have to think about that for a second.
 
Junilu Lacar
Sheriff
Posts: 11744
191
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nah, even if it was used on the left hand side of an assignment, there is still no real preference available since the two forms can't be functionally equivalent.
 
Junilu Lacar
Sheriff
Posts: 11744
191
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So again, I can't reconcile my experience with Ryan's claim that he has seen cases where it's actually preferable to use preincrement over post increment.

Maybe we're reasoning with different definitions of "preferable". Maybe he meant to say "suitable" or "appropriate" instead. If that's what he meant, then I can agree with it for reasons I have already gone over ad nauseum.
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I use i++ for for loops.
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Id do option A, its just better looking and more conventional, otherwise that's it though in the end it really shouldn't make a difference.
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Option A is the one I use because adds to i after each run of the loop instead of before.
 
Liutauras Vilda
Marshal
Posts: 5589
383
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Eli Richardson wrote:Option A is the one I use because adds to i after each run of the loop instead of before.


I thought we have discussed that extensively and came to concensus that it isn’t correct.

Why you writing that?
 
Ranch Hand
Posts: 1149
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:...

...

They cannot both be correct because the expressions result in different behavior of the for-loop. So in this case, there is no "preferring" one over the other since you can only use the form that results in the correct logic. 



True.  Where the use of post- versus preincrement operators makes a functional difference personal preference is meaningless.

My point is that in cases where it does make a difference, ++i is more likely to one that's needed.  If that's true, then I'd rather have had ++i become the standard rather than the exception. 

For instance...

In that code, I want i, j and k to all have the same value at the top of the loop.  If I had used k = j = i++, the second time through the loop, i would be 1 while j and k are still 0.

Mind you... it is just my gut feel with zero data to back it up that this type of scenario (where k = j = ++i is preferable to k = j = i++) is more prevalent than the opposite.  Maybe I'm completely off-base.

EDIT: Adding this (I hope) concise summary of my position:
The current situation, where i++ is the standard when it doesn't make a functional difference and ++i is more often needed when there is a difference, is unfortunate.
 
Ryan McGuire
Ranch Hand
Posts: 1149
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Ryan McGuire wrote:The current situation, where i++ is the standard when it doesn't make a functional difference and ++i is more often needed when there is a difference, is unfortunate.



And that holds for expressions in addition to the increment expression for for() loops.  I can't remember the last time I needed an expression to have the side effect of incrementing a variable and a value equal to the old value of the variable.  However, I can remember the last time I wanted to increment a variable and then immediately use the new value:



EDIT: Updated the wording of the first sentence without changing the meaning much.
 
Junilu Lacar
Sheriff
Posts: 11744
191
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:My point is that in cases where it does make a difference, ++i is more likely to one that's needed.  If that's true, then I'd rather have had ++i become the standard rather than the exception. 

For instance...

In that code, I want i, j and k to all have the same value at the top of the loop.  If I had used k = j = i++, the second time through the loop, i would be 1 while j and k are still 0.


Thanks, Ryan, for trying to examine this line of reasoning with me without getting defensive. I'm glad you took it the way I had hoped you would.

I fully agree with you about the (out loud) readability aspect of ++i that you described earlier. However—and I know you're just trying to make a point—this latest example you gave still fails to convince me that there's any compelling reason besides correctness of program logic to prefer to use ++i instead of i++.

The problem is related to what Campbell pointed out earlier: the examples we're giving are hardly "preferable" because they are examples of very poorly factored code. We can't ignore that and focus solely on the merit of ++i over i++.  The context is always important and if the context we use stretches the bounds of reason, then our "proof" or reasoning is also shaky. 

It's kind of like asking whether you'd prefer to die by heart attack or by drowning. Well, if you really think about it, any sane person would rather NOT die, right? So neither of the choices given is really a "preference". And saying "Well, if you HAD to make a choice" doesn't cut it either. We always have a choice to NOT write poorly factored code.

In your last example, the variables j and k presumably only start with the value of i in each iteration of the loop then subsequently change independently of i in the for-loop body.  Well, in that case, the variables j and k should not be included in the for-loop header since the only variable that factors into the loop control is the variable i.

With this refactoring, it's clear that only the variable i controls the loop iteration and now you're back to choosing between ++i or i++ as a matter of style and personal preference, not program correctness.
 
Campbell Ritchie
Marshal
Posts: 58319
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:. . . what Campbell pointed out  . . .

You can use size++ and --size with arrays for something like an array‑based stack:-If you haven't seen that sort of code before,
  • 1: I have omitted any handling of a full array from the push method.
  • 2: It may take several minutes for you to work out exactly what this code means.
  • That is one place where using ++ and -- inside other statements is respectable. The other place where it is respectable is in those horrible cert exam questions like:-

    If i and j are declared as type int, what will the following code print?A: 1
    B: 2
    C: 0
    D: -3249846519849816
    E: None of the above
    F: Code won't compile

    And my apologies for misunderstanding what you were showing yesterday.
     
    Junilu Lacar
    Sheriff
    Posts: 11744
    191
    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:And my apologies for misunderstanding what you were showing yesterday.


    No worries, Campbell. I'm surprised it doesn't happen more often to me given that my posts are usually TL;DR
     
    Ryan McGuire
    Ranch Hand
    Posts: 1149
    9
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Junilu Lacar wrote:
    Thanks, Ryan, for trying to examine this line of reasoning with me without getting defensive. I'm glad you took it the way I had hoped you would.

    I fully agree with you about the (out loud) readability aspect of ++i that you described earlier. However—and I know you're just trying to make a point—this latest example you gave still fails to convince me that there's any compelling reason besides correctness of program logic to prefer to use ++i instead of i++.



    Let me flip it back to you.  OTHER THAN ACCEPTED CONVENTION, is there any reason that i++ is better than ++i?  In the small percentage times where it makes a difference (such as implementing a stack with i++ and --i), did you find yourself using ++i or i++?  Why?

    And just so we're on the same page... I am not advocating that we change convention now.  I'm saying that in the alternate universe where there is no existing convention, I'd vote for ++i to become the convention.
     
    Liutauras Vilda
    Marshal
    Posts: 5589
    383
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Ryan McGuire wrote:And just so we're on the same page... I am not advocating that we change convention now.  I'm saying that in the alternate universe where there is no existing convention, I'd vote for ++i to become the convention.


    You may not know yet, Ryan, but Junilu sometimes can be hard to convince

    Interesting is, that when I read each of you posts, feels like a scales, leaning on one or another side. I guess you just both look from a different angle at it. But I think I understand you both.

    What Junilu is fighting for, is
    What he is actually saying (I think), that you can not put this down to convention, because there is nothing conventional in this situation, but rather completely different functionality if there were ++i.

    On the other hand, what Ryan is fighting for, is:
    So Ryan is saying, that if he were able to choose, he'd rather vote for ++i be a conventional way as inline increment in the situations when the convention kicks in and has no effect from functionality point of view, i.e. ++i wouldn't make difference.

    We see all, that these snippets are completely different and meant to do different things, so convention here and functionality can't be really merged.

    Some threads are complicated enough and there are a lot of stuff to discuss, so we do, but not always a lot. Some threads (like this), has not much to discuss, but we do, and we do a lot, and we seem to enjoy it - I didn't solve that puzzle yet and still can't recognize beforehand on which thread that kind of thing happen
     
    Greenhorn
    Posts: 4
    Java Mac OS X Netbeans IDE
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I prefer option A simply because it looks more correct, although both usually work.
     
    Liutauras Vilda
    Marshal
    Posts: 5589
    383
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    anjoulie alhaj wrote:I prefer option A simply because it looks more correct, although both usually work.


    Welcome to the Ranch.

    Well, probably we shouldn't judge statements on their look. When you say they both usually work, it isn't clear. They work always if you use them correctly (i.e. get syntax right), but there are tons of situations when they serve different functionality - so they are completely different, just in some cases appear to have no influence in the final result, but not in the mechanics how they (pre/post increments) work themselves.

    It seems much more people are confused about that than I assumed initially. Probably will have to concede with Junilu, that it is safer and easier just put conventional discussion away and rather concentrate on functionality they serve, because that is actually what it is after all.
     
    Campbell Ritchie
    Marshal
    Posts: 58319
    178
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I have seen lots of people get confused about ++ but hardly ever about ++i.
     
    Liutauras Vilda
    Marshal
    Posts: 5589
    383
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Shweta Chaudhary wrote:++i and i++both are use in for loop for increase 1 step size but ++i first increase one step than execute the code written inside the for loop and i++ firstly execute the code written inside the for loop than increase one step.


    All wrong. Read preceding posts for correct explanation.
     
    Junilu Lacar
    Sheriff
    Posts: 11744
    191
    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:Let me flip it back to you.  OTHER THAN ACCEPTED CONVENTION, is there any reason that i++ is better than ++i? ... And just so we're on the same page... I am not advocating that we change convention now.  I'm saying that in the alternate universe where there is no existing convention, I'd vote for ++i to become the convention.


    No, there isn't. And yes, we're on the same page. I like your read-it-as-"Increment i" readability reason and in alternate universe, I'd probably vote that way, too.

    In the small percentage times where it makes a difference (such as implementing a stack with i++ and --i), did you find yourself using ++i or i++?  Why?


    Uhmm... because it makes a difference?

    Did you mean to write "where it doesn't make a difference" instead? When it doesn't make a difference, that is, when there's actually a choice, I prefer to follow convention. But I've only beaten that horse a hundred times already.

     
    Junilu Lacar
    Sheriff
    Posts: 11744
    191
    Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I see a number of digressions from the original question, which was qualified by "use ... in for-loops".  All through this thread, I have discounted any reasoning that involves anything other than choosing to use either ++i or i++ in the ForUpdate part of a classic for-loop header.

    So let me just swing one more stroke at the dead horse and summarize what I've been saying: In the ForUpdate part of a classic for-loop, given the choice between using a solitary ++i or i++, and either of these provide the correct logical behavior , I would prefer to follow convention and use i++ post-increment because that's what most people are used to seeing. I agree with Ryan that ++i reads more naturally if you read it out loud as "increment i".
     
    Rancher
    Posts: 940
    9
    Java Linux Spring
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Maybe I'm getting old [and grumpy], but I prefer boring standard code, so its i++ for me. 
    The discussion above tells me that there is a still a lot of confusion about i++, ++i, (i++), (++i) etc.  ++i is a bad smell when everyone else is using i++

    Another issue is that most systems are maintained many years after the original team have delivered them, then all that "clever quirky" code becomes a costly maintenance nightmare!
    I guess the real "art" is to make the complex solution, look simple - and not the other way around.

    As for performance, Knuth said it right --> "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%."

        
     
    Greenhorn
    Posts: 19
    Eclipse IDE Java VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    When I first learned Java many years ago, I was i++ for me and not much has changed in the years since. 
     
    Campbell Ritchie
    Marshal
    Posts: 58319
    178
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Welcome to the Ranch SJ
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!