Will the strlen() function below get called just once (with the value stored for further comparisons); or is it going to be called every time the comparison is performed?
for (i = 0; i < strlen(word); i++)
{ /* do stuff */ }
Will the strlen() function below get called just once (with the value stored for further comparisons); or is it going to be called every time the comparison is performed?
for (i = 0; i < strlen(word); i++)
{ /* do stuff */ }
It will be evaluated for every iteration of the loop (edit: if necessary).
Like Tatu said, if word
isn't going to change in length, you could do the strlen
call before the for loop. But as Chris said, the compiler may be good enough to realize that word
can't change, and eliminate the duplicate calls itself.
But if word
can change in length during the loop, then of course you'll need to keep the strlen
call in the loop condition.
That's implementation-dependent. Usually, it gets called every time, but, if the compiler can see that word
never changes, and that strlen
is a pure function (no side effects), it can lift the call.
See: http://underhanded.xcott.com/?page_id=15 for a well-known example of this being exploited. :-)
strlen checks the lenght of the provided string. Which means that if the lenght is 10. Your iteration will keep on going as long as i is below 10.
And in that case. 10 times.
I'll sometimes code that as ...
for (int i = 0, n = strlen(word); i < n; ++i) { /* do stuff */ }
... so that strlen is only called once (to improve performance).
It will be called for each iteration. The following code only calls strlen function once.
for (i = 0, j = strlen(word); i < j i++)
{ /* do stuff */ }
The number of times strlen(word)
is executed depends on:
word
is declared as constant (the data is constant)word
is not changed.Take the following example:
char word[256] = "Grow";
for (i = 0; i < strlen(word); ++i)
{
strcat(word, "*");
}
In this example, the variable word
is modified withing the loop:
0) "Grow" -- length == 4
1) "Grow*" -- length == 5
2) "Grow**" -- length == 6
However, the compiler can factor out the strlen
call, so it is called once, if the variable word
is declared as constant:
void my_function(const char * word)
{
for (i = 0; i < strlen(word); ++i)
{
printf("%d) %s\n", i, word);
}
return;
}
The function has declared that the variable word
is constant data (actually, a pointer to constant data). Thus the length won't change, so the compiler can only call strlen
once.
When in doubt, you can always perform the optimization yourself, which may present more readable code in this case.