Reputation: 1512
for example,we have code like this:
for (i = 0; i < function(); ++i )
{
// loop body;
}
will the function() be evaluated for each loop?
Upvotes: 4
Views: 946
Reputation: 98766
Yes, in all three languages.
To avoid this, you can put the result of function()
into a variable:
int funcVal = function();
for (i = 0; i < funcVal; ++i) {
// ...
}
The compiler/JVM can't optimize this away for you (except in certain trivial cases) because function()
might have a side-effect, for example printing to the console.
Upvotes: 3
Reputation: 533530
Similar to @Cameron's answer, you can write
for(int i = 0, funcVal = function(); i < funcVal; ++i) {
// ...
}
As @RollingBoy suggests, the function() can be in-lined in C++ (by the compiler) and Java (by the JVM) and possibly optimized so it is not evaluated more than once.
Upvotes: 1
Reputation: 162801
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.
Upvotes: 7
Reputation: 2817
It depends.
In most cases, the function will be called mutiple times.
However:
In C++, if it's a very simple function and make 'inline', then it's possible that there's no function call there indeed.
And in Java, if it's simple as well, JIT of VM may optimize it to reduce the unnecessary calls.
Upvotes: 1