1

BESIDES having to do a bunch of unnecessary iterations in a for loop with strlen doesn't it also produce weird behaviors?

http://www.cprogramming.com/tips/tip/dont-use-strlen-in-a-loop-condition

The documentation uses size_t instead of int. I believe I got weird behaviors when it happened. I didn't write it down when it happened so I can't remember where to look.

http://www.cplusplus.com/reference/cstring/strlen/
http://www.tutorialspoint.com/c_standard_library/c_function_strlen.htm

Votes + Comments
Hey, I like the question.
4
Contributors
3
Replies
19
Views
2 Years
Discussion Span
Last Post by ddanbe
0

One of my rules is that you NEVER use a function as the terminating condition in a loop. This is only necessary if the output of that function may change during the loop. In this case, it does not, so do this instead (taken from the cplusplus.com article:

for ( int ix = 0, jx = strlen(a_str); ix < jx; ix++)
{
     a_str[ix] = tolower( (unsigned char) a_str[ix] );
}
0

I agree with rubberman. A function in a loop just wastes time if you evrey time through the loop, want the same value from it. I would call it before the loop

int length = strlen(a_str);
for ( int ix = 0, ix < length;  ix++)
{
     a_str[ix] = tolower( (unsigned char) a_str[ix] );
}

And if you want to avoid it alltogether use

int i=0;  
while (a_str[i])
{  
    a_str[i] = tolower((unsigned char)a_str[i]);
    i++;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.