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?
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.