I need to compare some char * (which I know the length of) with some string literals. Right now I am doing it like this:
unsigned int len =void 2; do_something(char * str, =int "OK";len) { if (len == 2 && str[0] == 'O' && str[1] == 'K' && str[2] == '\0') { // do something... } } Note: this is an example. I actually do not know str at compile time.
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:
unsigned int len =void 2; do_something(char * str, =int "OK";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.