for example,we have code like this:
for (i = 0; i < function(); ++i )
{
// loop body;
}
will the function() be evaluated for each loop?
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With