Gristly
Gristly

Reputation: 53

Adding extra code to the increment step of a for loop

Student who enjoys programming here. I've been programming with java for 4 years, and I feel like I have a fairly good understanding of how the language works. Recently, however, I stumbled on something that surprised me quite a bit. While thinking about for loops, I thought "Hey the increment part of a for loop is just an operation, can I put other things in there?" and eventually after some playing around I decided to try this:

for(int i = 0; i < 10; i++, System.out.print("foo"), System.out.print("bar")){}

This is a totally empty for loop, with the print calls inside the loop's increment step. To my surprise, this loop functions correctly, and every time it loops it prints foo and bar. As far as I can tell, you can put as many methods in there as you'd like.

So what is this? I searched for it and didn't find anything. I've never learned about this. Should it be avoided? Should it be used? Why does it even work? I can't find any resources that show examples of this in use. Any input from real programmers would be great to hear!

Upvotes: 4

Views: 118

Answers (3)

Keiwan
Keiwan

Reputation: 8301

Well, you can think of a for loop as a while loop that provides you with some "nice" formatting: So for example the loop

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

is the same as:

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

Notice that the for loop basically just takes whatever you write in the increment part and puts it at the end of the loop, just before it jumps back to the start. So everything you put there will essentially be added to the end of the code inside of the loop. You can try out with this maybe get a better idea of what is happening:

for(int i = 0; i < 5; System.out.println("i before" +  i),i++,   System.out.println("i after" + i)){ 
    System.out.println("Inside");
}

Which prints out:

Inside
i before0
i after1
Inside
...

Just as a sidenote: I would definitely not use it like that, since it just makes the code harder to understand and there is not real benefit to it.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692231

This is covered by the Java Language Specification. Extract:

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

Should it be used? In my opinion, no. It makes the code harder to read, and isn't idiomatic at all.

Upvotes: 8

Mr. DROP TABLE
Mr. DROP TABLE

Reputation: 332

The syntax of the for loop is simply a shortened way of writing out several lines of code. The first part is initialization, the second is a conditional, and the third is whatever you want! (in most cases an iterator). Most people don't put anything else in there because it seems odd, or they just like to organize their code a specific way.

Upvotes: 0

Related Questions