What is the best alternative to calling strlen() in my for loop condition in C?
c, for-loop, string
Solution
The second one is usually preferred.
The other popular form is
for (char* p = something; *p; p++)
{
// ... work with *p
}
Yet another one is
char* p = something;
char c;
while ((c = *p++))
{
// ... do something with c
}
(the extra `()` around assignment are needed to make some suspicious compilers not issue a warning stating I might mean comparison inside `while` condition)
Indeed, `strlen` is quite slow, because it must go through the whole string looking for trailing 0. So, `strlen` is essentially implemented as
int s = 0;
while (*p++) s++;
return s;
(well, in fact a slightly more optimized assembler version is used).
So you ought to avoid using `strlen` if possible.
Problem
I've read that it is bad practice to call strlen() in my for loop condition, because this is an O(N) operation. However, when looking at alternatives I see two possible solutions: ``` int len = strlen(somestring); for(int i = 0; i < len; i++) { } ``` or... ``` for(int i = 0; somestring[i] != '\0'; i++) { } ``` Now, the second option seems like it might have the advantage of 1) not declaring an unnecessary variable, and 2) should the string length be modified in the loop it should still reach the end as long as the length isn't < i. However, I'm not sure. Which one of these is standard practice among C programmers?