Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++/Java question: will the expression used in for loop evaluate multiple times?

Tags:

java

c++

c

for example,we have code like this:

for (i = 0; i < function(); ++i )
{
   // loop body;
}

will the function() be evaluated for each loop?

like image 564
PeopleMoutainPeopleSea Avatar asked Dec 16 '22 15:12

PeopleMoutainPeopleSea


1 Answers

Yes. It will be evaluated in each iteration of the loop. It must be because the there is a possibility that the function can return a different value each time it is called. Also, there may be a side-effect of calling the function (e.g. changing the value of a variable or writing a file). The compiler cannot assume otherwise. If that behavior is not desirable, you can use this for loop syntax to do only 1 calculation:

for (i = 0, len=function(); i < len; ++i )
{
   // loop body;
}

Update:

Some have noted that there are certain edge cases where compilers can optimize away the multiple calls: e.g. const or inline functions in C++ that have no side effects, or a possibly when the JVM can infer that the function is repeatable and has no side-effects. But if you want a guarantee, and not rely on something that a compiler might do for you, I still recommend the for loop syntax mentioned above.

like image 118
Asaph Avatar answered Jan 11 '23 22:01

Asaph