C string compare function

Programming, for all ages and all languages.
Post Reply
User avatar
IanSeyler
Member
Member
Posts: 326
Joined: Mon Jul 28, 2008 9:46 am
Location: Ontario, Canada
Contact:

C string compare function

Post by IanSeyler »

Code: Select all

/* string compare
 * returns 0 if equal, 1 if not equal
 */
int str_cmp(unsigned char str1[], unsigned char str2[])
{
        int i = 0;

        if (str1[0] == '\0' && str2[0] == '\0') // Check if both strings are empty
                return 0;

        for (i=0; str1[i] != '\0'; i++) // Compare strings until end of first
        {
                if (str1[i] != str2[i])
                        return 1;
        }

        if (str2[i] != '\0') // Check to make sure str2 was same length
                return 1;

        return 0; // Otherwise they are equal
}
Does anyone see any glaring issues or use cases I might have missed? It works in testing without any problems.
BareMetal OS - http://www.returninfinity.com/
Mono-tasking 64-bit OS for x86-64 based computers, written entirely in Assembly
Icee
Member
Member
Posts: 100
Joined: Wed Jan 08, 2014 8:41 am
Location: Moscow, Russia

Re: C string compare function

Post by Icee »

Does this have to be so complicated and non-standard?

Code: Select all

int
strcmp(const char *s1, const char *s2)
{
    while ((*s1 == *s2) && *s1) { ++s1; ++s2; }
    return ((int) (unsigned char) *s1) - ((int) (unsigned char) *s2);
}
User avatar
IanSeyler
Member
Member
Posts: 326
Joined: Mon Jul 28, 2008 9:46 am
Location: Ontario, Canada
Contact:

Re: C string compare function

Post by IanSeyler »

:shock: Wow. Apparently C isn't exactly my forte.
BareMetal OS - http://www.returninfinity.com/
Mono-tasking 64-bit OS for x86-64 based computers, written entirely in Assembly
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re: C string compare function

Post by Solar »

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!
Every good solution is obvious once you've found it.
User avatar
Brendan
Member
Member
Posts: 8561
Joined: Sat Jan 15, 2005 12:00 am
Location: At his keyboard!
Contact:

Re: C string compare function

Post by Brendan »

Hi,

Nobody ever considers doing an initial "if(s1 == s2) return 0; // Both pointers point to the same thing!"... ;)


Cheers,

Brendan
For all things; perfection is, and will always remain, impossible to achieve in practice. However; by striving for perfection we create things that are as perfect as practically possible. Let the pursuit of perfection be our guide.
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re: C string compare function

Post by Solar »

Adding a condition to every call to optimize for a rather special case...?

I considered but opted against it.
Every good solution is obvious once you've found it.
User avatar
Schol-R-LEA
Member
Member
Posts: 1925
Joined: Fri Oct 27, 2006 9:42 am
Location: Athens, GA, USA

Re: C string compare function

Post by Schol-R-LEA »

Don't look at me here. Like captive orcas, I'm leaving C world for good as soon as I can (but probably not very soon at all, and maybe not ever - again, like the whales, who are, after all, hard to move, being almost as heavy as I am).

(Yeah, I know it is rather silly to interject into a thread just to make a joke, but I needed to make light of developments - or lack thereof - in my own projects a bit.)
Rev. First Speaker Schol-R-LEA;2 LCF ELF JAM POEE KoR KCO PPWMTF
Ordo OS Project
Lisp programmers tend to seem very odd to outsiders, just like anyone else who has had a religious experience they can't quite explain to others.
User avatar
dozniak
Member
Member
Posts: 723
Joined: Thu Jul 12, 2012 7:29 am
Location: Tallinn, Estonia

Re: C string compare function

Post by dozniak »

Schol-R-LEA wrote: (Yeah, I know it is rather silly to interject into a thread just to make a joke, but I needed to make light of developments - or lack thereof - in my own projects a bit.)
There's quite a bit of you in the threads lately. Sometimes even 2-3 posts in a row (which is against the forum rules here). Nothing to do?
Learn to read.
User avatar
iansjack
Member
Member
Posts: 4685
Joined: Sat Mar 31, 2012 3:07 am
Location: Chichester, UK

Re: C string compare function

Post by iansjack »

It's good to have a representative of the forums explain the rules to us. However, it would be useful if this restriction actually appeared in the published rules (else we are working in the dark). Can I trust that you will arrange for this explanation of the forum rules?

(Personally, I think that a multitude of interesting and informative posts are of more value than a single one that adds nothing to the topic under discussion. But it's your forum, not mine, so you get to make the rules.)
User avatar
Schol-R-LEA
Member
Member
Posts: 1925
Joined: Fri Oct 27, 2006 9:42 am
Location: Athens, GA, USA

Re: C string compare function

Post by Schol-R-LEA »

dozniak wrote:
Schol-R-LEA wrote: (Yeah, I know it is rather silly to interject into a thread just to make a joke, but I needed to make light of developments - or lack thereof - in my own projects a bit.)
There's quite a bit of you in the threads lately. Sometimes even 2-3 posts in a row (which is against the forum rules here). Nothing to do?
Pretty much. Or rather, no will to do most of the things I should be doing. Posting here is mostly a 'retreating from the world' thing for me lately.

As for the multiple sequential posts, I usually try to edit existing posts instead, but I have been finding myself editing posts days or even weeks later in some cases, meaning that the additions and corrections go unseen.

Also, too often it triggers "TL;DR", especially in the people I am actually trying to get through to.

However, the MSP approach seems to be failing in that regard, too, as they simply aren't reading the posts at all now.
Rev. First Speaker Schol-R-LEA;2 LCF ELF JAM POEE KoR KCO PPWMTF
Ordo OS Project
Lisp programmers tend to seem very odd to outsiders, just like anyone else who has had a religious experience they can't quite explain to others.
User avatar
dozniak
Member
Member
Posts: 723
Joined: Thu Jul 12, 2012 7:29 am
Location: Tallinn, Estonia

Re: C string compare function

Post by dozniak »

Schol-R-LEA wrote: Also, too often it triggers "TL;DR", especially in the people I am actually trying to get through to.

However, the MSP approach seems to be failing in that regard, too, as they simply aren't reading the posts at all now.
The wall of text posts do have their detracting effect in this ADHD era.
Learn to read.
Post Reply