When I stumbled into this piece of C code, at first, it looked not so bad to me.

void foobar(const char *par)
{
        if (!strcmp(par, "FirstString")) {
                // do something
        } else if (!strcmp(par, "SecondString")) {
                // do something else
        } else ...
}

The real function contains more than twenty comparisons and some strings are quite long and complicated. At first I thought this was needed to parse command line arguments or a user input. Unfortunately it wasn't. This is a perfect example of stringly typed[1].

In another part of the program, this function is called multiple times, based on several conditions and the strings passed are all hard-coded.

        if ( /* condition */ )
                foobar("FirstString");
        else if ( /* other condition */ )
                foobar("SecondString");
        ...

Let's pretend to ignore for a moment the fact that the code in the first function can be put in the second one. But really it makes no sense to use literal strings to do something that can be done really better with enumerators or even with integer defines.


Cover image by Aldo Cavini Benedetti taken from Flickr licensed under the Creative Commons Attribution NonCommercial ShareAlike 2.0 Generic license.

This post has been updated after its initial publication. Last change made on 2016/11/06.


  1. Stringly typed: see point 7 in this old Coding Horror post. ↩︎