Search code examples
cperformanceif-statementboolean-logicstrcmp

Among several given ways to test a string against two possible values using strcmp, is one of them an obvious choice?


I wish to test a string against "y" and "yes" and if it is either, do something. (Well, not really but this is the equivalent of the real code.) The following three ways of doing the test in C are logically equivalent. I am curious how more experienced programmers would choose among these possibilities and why.

if ( strcmp(mystring,"y")==0 || strcmp(mystring,"yes")==0 ) { something(); }

if ( !strcmp(mystring,"y") || !strcmp(mystring,"yes") ) { something(); }

if ( !(strcmp(mystring,"y") && strcmp(mystring,"yes")) ) { something(); }

Each of these has pros and cons. I am also aware that it's best to write code that is easiest to read and maintain. What's unclear to me is whether most C programmers would consider the second as easy or easier to read than the first. If so, then its shorter length makes it the best choice of the three. (The third seems extra confusing to read so despite its lower number of max operations, doesn't seem the best choice.)

Maybe something I didn't even consider is best like

if ( strcmp(mystring,"y") && strcmp(mystring,"yes") ) {} else { something(); }

Solution

  • Unless there are known performance issues with one approach vs another, always prefer the approach that is easier to read and understand.

    Given your three choices, I would most definitely go with:

    if ( strcmp(mystring,"y")==0 || strcmp(mystring,"yes")==0 ) { something(); }
    

    Update

    You can define a macro that will help make it more straight forward and easy to read.

    #define STRING_EQUAL(A, B) (strcmp((A), (B)) == 0)
    
    if ( STRING_EQUAL(mystring,"y") || STRING_EQUAL(mystring,"yes") ) { something(); }