2OF1 · the depletionmode zineLinkedIn · X
← back to the issue

23 November 2010

Making sense of strcmp()

Originally published on the old depletionmode / 2of1 blog (archived copy).

Peter van der Linden brought up a point regarding strcmp() his book Expert C Programming: Deep C Secrets that I found interesting.

The issue is that strcmp() returns exactly the opposite of what one would logically expect.

Do something if string1 IS EQUAL to string2 needs to be implemented as Do something if NOT strcmp(string1, string2) which is weird as one one would have thought that strcmp() – being a function that COMPARES two strings – would logically return TRUE if the strings actually match, when in fact it returns 0 – i.e. meaning that there is no mismatch at any character in the string.

I’ve often wondered about this – and it certainly doesn’t confuse me – but there’s still something weird about writing code that doesn’t translate logically.
Initially I used the ! (logical NOT) operator as in *if (**!*strcmp()) – but I felt that the meaning wasn’t clear at all. My current use is usually in the form of if (strcmp() == 0).

However, as Peter van der Linden points out, neither make much logical sense.
He suggests using the following macro to clear things up:

#define STRCMP(a,R,b) (strcmp(a,b) R 0)

Which can be used like so:

if (STRCMP(s, ==, “string”))

However I think that this should be simplified even further.
Think of it this way: if we are interested in whether strings match or not – i.e. return TRUE on match, FALSE otherwise) – then we should just simply have a macro that provides that.
I’d suggest modifying Peter’s macro to something like:

#define STRCMP(a,b) (strcmp(a,b) == 0)

In my opinion there is no need for the R as this is logically implicit in the results that we want.
However the issue is that when one who is familiar with strcmp() sees a STRCMP() macro in the code, they may misunderstand it’s meaning and assume it returns values in the same backwards logic that strcmp() does. This could lead to serious bugs in the code!

In order to address this, I suggest naming the macro something else entirely in order to avoid confusion and have the code read exactly as it functions.
Maybe something like STRISEQUAL or STRMATCHES.

→ end of entry

2/1
@depletionmode
security research & systems engineering