Adding additional code to the for loop increment step

A student who likes to program here. I have been programming with java for 4 years and I feel like I have a pretty good idea of ​​how the language works. Recently, however, I came across something that surprised me quite a bit. While I was thinking about loops, I thought, “Hey, the incremental part of the for loop is just an operation, can I put other things in there?” and in the end, after some games, I decided to try:

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

This is a completely empty for loop, with print calls inside the loop increment step. To my surprise, this loop functions correctly, and each time it loops, it prints foo and bar. As far as I can tell, you can use as many methods as you want.

So what is it? I searched for him and found nothing. I never found out about it. Should it be avoided? Should it be used? Why does it work? I can not find any resources that show examples of this in use. Any input from real programmers would be great!

+4
source share
3 answers

This is covered by the Java Language Specification . Exposure:

if part of ForUpdate is present, expressions are evaluated sequentially from left to right; their values, if any, are discarded.

Should it be used? In my opinion, no. This makes the code more difficult to read and not idiomatic at all.

+8
source

for - . - , - , - , ! ( ). , , .

0

, for while, "" : ,

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

:

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

, for , , , , . , , , . , , , :

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

:

Inside
i before0
i after1
Inside
...

Just like a side element: I would definitely not use it like that, because it just makes the code more difficult to understand, and there is no real benefit to it.

0
source

All Articles