java - Are functions inside a for loop's condition statement executed every time? -


this question has answer here:

if have loop so:

for(int = 0; < getint(); i++){//code} 

will getint() executed every time loop checks if:

i < getint(); 

or executed once @ beginning , return value j loop check if:

i < j; 

the specific language i'm wondering java if answer differs in other languages know well.

yes, executed every loop.

basically, execution goes this:

  1. the first part of for condition executed once
  2. the second part evaluated, if it's true body of loop executes. otherwise, go statement following loop.
  3. after body executed, third part (i++ here) executed
  4. go 2.

it make no sense second part (the continuation condition) not evaluated every time. if in body of loop causes getint() return different value between iterations?

of course, compiler free perform optimizations around constant expressions , other things can prove. example, if getint() defined such:

public int getint() {   return 4; } 

your compiler could

  1. emit code equivalent for(int = 0; < 4; i++) { //body }
  2. remove loop , emit body of loop 4 times necessary adjustments
  3. not care , emit un-optimized code.

in cases getint() called, in other cases wouldn't. in cases compiler right because perform transformations result in code behaves as-if transformations weren't performed.


Comments