Some notes on computer stuff

strchr() finds zero character

October 17, 2012
[programming] [c] [c++] [strchr] [issue]

As any other programmer once in a while I find some new tiny but quite useful trick, which I then apply to my sources. One of such trick is using of strchr() function to compare if a value of type char equals to one of values.

Usually one will write something like:

int test_char(char c)
{
    return (c == 'a' || c == 'b' || c == 'x');
}

With help of strchr() one can the code with a bit simpler one:

int test_char(char c)
{
    return strchr("abx", c) != NULL;
}

Which at least looks cleaner for me, which doesn't matter much in this case, but will matter in case of five of more comparison statements.

So after replacing several comparisons in the code I was going to commit it. But what a surprise: some of tests have failed (it's always nice to have tests). After standard procedure of staring at the code, I didn't have any ideas of what could go wrong, the logic should remain the same. The next step was to run a debugger, which has uncovered the truth: the strchr() function thinks that ending '\0' character is a part of the string. And it's explicitly documented by the standard (a good reason to read it till the end one day). So instead of comparing c to a, b and x, the code bassically became like this:

int test_char(char c)
{
    return (c == 'a' || c == 'b' || c == 'x' || c == '\0');
}

Which is wrong. I'm still using strchr() function when appropriate to do such multiple comparisons, but now I know more about its behaviour (and also being curious why it is so?).