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?
strlen() in C-style strings can be replaced by C++ std::strings. sizeof() in C is as an argument to functions like malloc(), memcpy() or memset() can be replaced by C++ (use new, std::copy(), and std::fill() or constructors).
C strlen() The strlen() function calculates the length of a given string. The strlen() function takes a string as an argument and returns its length. The returned value is of type size_t (an unsigned integer type). It is defined in the <string.
The syntax of the strlen() function is: strlen(const char* str); Here, str is the string whose length we need to find out, which is casted to a const char* .
The strlen() function in C is used to calculate the length of a string. Note: strlen() calculates the length of a string up to, but not including, the terminating null character. Return Value: The function returns the length of the string passed to it.
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.
These are preferred:
for (int i = 0; str[i]; ++i)
for (char* p = str; *p; ++p)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With