Icee handled the optimization well. (And yes, if you're doing indexed string access in most of C's string-related functions, you're doing it wrong.) Let's have a look at style.
Code: Select all
int str_cmp(unsigned char str1[], unsigned char str2[])
If you're implementing something that's
almost a standard function,
make it the standard function. From a maintenance / intuition standpoint, having something that is
almost but not quite a strcmp() is a bad idea. Check chapter 7 of the standard document for a very good and, most of all,
precise description of the standard functions. (Some of them, like strncpy(), are notoriously badly understood by many.)
The final draft (which is for most intents and purposes identical to the finished standard) is
n1570.
Your declaration makes it
look as if the function receives two
arrays as parameters. But it doesn't, it receives two
pointers (because that is what an array "dumbs down to" when passed as a parameter). You will notice the difference if you apply sizeof to the parameters. So don't make your declaration lie about what is happening.
A string is a sequence of char --
not unsigned char. Making your compare function operate on unsigned char, you will get
lots of conversion warnings.
It is correct that the actual difference is computed "as if operating on unsigned char" (that's the wording in the standard), and that is the purpose of the casts in Icee's code.
And if you're looking for some no-strings-attached example code for many standard functions, may I shamelessly advertise
PDCLib...
Personal code nitpicks:
Always use {} even for one-line loop / conditional bodies. Use space padding inside parenthesis and around operators. Use parenthesis around subexpressions in conditionals. I know there are arguments
against each of these as well, but after 15+ years of doing (mostly) C++ maintenance coding, I came to appreciate code that focusses on clarity of intent and verbose readability over most other concerns.
Cheers on the comments, they are spot-on, refreshing to see!