Search code examples
ccharstrcmpstrncmp

How to compare char* to string literal in C?


I need to compare some char * (which I know the length of) with some string literals. Right now I am doing it like this:

void do_something(char * str, int len) {
  if (len == 2 && str[0] == 'O' && str[1] == 'K' && str[2] == '\0') {
    // do something...
  }
}

The problem is that I have many comparisons like this to make and it's quite tedious to break apart and type each of these comparisons. Also, doing it like this is hard to maintain and easy to introduce bugs.

My question is if there is shorthand to type this (maybe a MACRO).

I know there is strncmp and I have seen that GCC optimizes it. So, if the shorthand is to use strncmp, like this:

void do_something(char * str, int len) {
  if (len == 2 && strncmp(str, "OK", len) == 0) {
    // do something...
  }
}

Then, I would like to know it the second example has the same (or better) performance of the first one.


Solution

  • Your example implies that your strings are always NUL terminated. In that case, don't bother getting their length ahead of time, since that involves searching for the NUL. Instead, you can do

    memcmp(str, "OK", 3);
    

    This way, the NULs get compared too. If your length is > 2, the result will be > 0 and if it's shorter, the result will be < 0.

    This is a single function call, and memcmp is virtually guaranteed to be better optimized than your hand-written code. At the same time, don't bother optimizing unless you find this code to be a bottleneck. Keep in mind also that any benchmark I run on my machine will not necessarily apply to yours.

    The only real reason to make this change is for readability.