In studying for the OCP Java Programmer Exam, I was slightly surprised to see this is legal syntax:
for(int i = 0; i < 3; i++, System.out.print("howdy ")) ;
This got me thinking! On testing some similar things I found this doesn’t compile:
for(;; int j = 0) ;
Couldn’t find much info on this. Could anyone provide a reference or explain why declaring a new variable in the incrementer part doesn’t compile but other statements (method calls etc.) do? And is it just (for loop scoped) variable declarations or are any other types of statements not allowed here?
A lot of statements are valid (see the link provided by alexei), but you have to take a look at the scope of the expressions to understand why this initializing wouldn’t work:
The scope is over all iterations of the for loop (rather than a new scope each time). The first part gets executed only once, but the second and third get executed at the end of each loop. Hence if you put a declaration in the third part, it gets declared several times (which isn’t allowed).