Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 322
Gristly Avatar asked Feb 06 '23 20:02

Gristly


1 Answers

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.

like image 87
JB Nizet Avatar answered Feb 24 '23 04:02

JB Nizet