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

rproffitt commented: Hey, I like the question. +6

Recommended Answers

All 3 Replies

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] );
}

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++;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.