0

If a function is part of the loop-test in a FOR loop, is that function called on every iteration of the loop or only the first iteration to setup the loop.

e.g.

for (i = 0; i < strlen(someString); i++) {
    // Do Something 
}

Is it better form to define a variable before the loop, whose value is the string length?

e.g.

int length = strlen(someString);

for (i = 0; i < length; i++) {
    // Do Something
}
  • 1
    Ask yourself, would it evaluate if you replaced your test expression with a function call: `for (int i = 0; isDone(i); i++) { ... }` I think you know the answer, so I think you know the answer to your question. :) – Kirk Woll Jan 12 '11 at 00:07

2 Answers2

0

Yes, the condition in a for loop is checked on every iteration. If the function you're calling there is at all expensive, then you should definitely store the value in a variable. However, if you have a short loop, it really won't make a difference.

Sam Dufel
  • 17,560
  • 3
  • 48
  • 51
0

It depends on the language (and if there is a method call as part of the test, and whether the compiler can determine if the method call will not change each iteration)

For instance, in some situations VB.NET evaluates once, c# evaluates each time.

There was a recent SO question that illustrated this: Why does C# execute Math.Sqrt() more slowly than VB.NET?

Community
  • 1
  • 1
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541