T
Tim Rentsch
William Krick said:Tim said:William Krick said:Tim Rentsch wrote:
One final revision. I've modified the return statement so that it
returns -1 / 0 / 1 to bring it in line with the behaviour of other
similar functions...
int str_ccmp( const char *s1, const char *s2 )
{
int c1, c2;
for(;
{
c1 = tolower( (unsigned char) *s1++ );
c2 = tolower( (unsigned char) *s2++ );
if (c1 == 0 || c1 != c2)
return c1 == c2 ? 0 : c1 > c2 ? 1 : -1;
}
}
If the tests are written differently, the return values
might be somewhat clearer:
int
str_ccmp( const char *s1, const char *s2 ){
int c1, c2;
for( ; ; s1++, s2++ ){
c1 = tolower( (unsigned char) *s1 );
c2 = tolower( (unsigned char) *s2 );
if( c1 > c2 ) return 1;
if( c1 < c2 ) return -1;
if( c1 == 0 ) return 0;
}
}
Actually, when you cleaned up the return conditions, you left out some
of the conditions and broke the code. [snip]
If you look again I think you'll see that the posted function
does indeed work properly. Here is the same function with some
assertions added -- see if you agree.
int
str_ccmp( const char *s1, const char *s2 ){
int c1, c2;
for( ; ; s1++, s2++ ){
c1 = tolower( (unsigned char) *s1 );
c2 = tolower( (unsigned char) *s2 );
if( c1 > c2 ) return 1;
if( c1 < c2 ) return -1;
assert( c1 == c2 );
if( c1 == 0 ) return 0;
assert( c1 == c2 && c1 != 0 );
}
}
Note that each of the 'return' statements is executed only if the
condition 'c1 != c2 || c1 == 0' is true, because of the 'if'
tests; it's not necessary to test for it separately.
I'll be damned. You're right. My bad.
Even though that is clearer, it would probably be a little slower since
there's 3 comparisons being done on each loop vs two in this version
[...]
Just a few quick reactions:
1. It's almost always better to put clarity concerns ahead of
concerns about micro-optimization.
2. We don't know that the generated code will have three
comparisons in the main path of the loop; it could be
optimized to only two (and not unreasonable to guess that
it might be).
3. Even if there are three conditional branches, they won't
necessarily run slower than two - depends on how the
branches are predicted, etc.
4. Performance decisions should be based on measurement.
5. Any differerence is highly unlikely to be on the critical
path. ("Premature optimization is the root of all evil.")