Stupid strcmp

Korey Hinton —> Blog —> Stupid strcmp

Unreadable Code using strcmp


int builtin_command(char **argv)
        return 1;
    return 0;

I saw this code block in my CSAPP textbook and it took me a while to figure out what it meant. Maybe I've been coding in Objective-C too long. When I tried to read the line if (!strcmp(argv[0],"quit")) I thought it meant if the strings are not equal. In English this line reads "if the strings don't compare". What does that even mean? I can take that to mean equality or inequality. It actually means equality in this case. Why are we using a not operator to mean equality? I had to look at the definition of strcmp to figure out what's going on:

The strcmp() function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.

Ok so what is really going here is that it evaluates to 0 if they exactly match. Wouldn't it be more readable if we re-wrote it like this?:

if(strcmp(argv[0],"quit") == 0)

If it really is best practice to shorten it and use a not operator, shouldn't it read better if we called it something like strdiff? Anyway I think some C coders could learn a lesson or 2 from its Objective-C superset: "Clarity and brevity are both important, but clarity should never be sacrificed for brevity." ~ Cocoa Core Competencies.

If we really wanted to make the code harder on the reader why not just add a couple more nots?:

if (!!!!!strcmp(argv[0],"quit"))

Lesson in C learned for the day: When reading C code, take the language reference with you!

Date: 2014-12-19T05:24+0000

Author: Korey Hinton

Org version 7.9.3f with Emacs version 24

Validate XHTML 1.0