user5042178
user5042178

Reputation:

Compare character with multiple characters in C

How can i compare a character in C with other characters without using an 'if' with tons of '||'? For example let's say I have a character named 'i' that I want to compare with 8 other characters that have no connection between them whatsoever, and if 'i' equals to at least one of those 8 characters then the expression is true. Something like this:

if(i == c1 || i == c2 || i == c2 ........){ /* do stuff */}

But on a big application these comparisons are a lot, not just 3 or 8. Is there a smart and fast way to achieve something like this and not end up with ugly looking code? Thank you in advance.

Upvotes: 0

Views: 4613

Answers (1)

too honest for this site
too honest for this site

Reputation: 12263

Assuming your 'c1', ... are just a single char constants, you can use:

if ( strchr("12345", ch) != NULL )
    ...

("12345" are c1, c2, ...)

strchr() will, however, also match the implcit trailing NUL terminator ('\0'). If that is a problem, you can compare this value explicitly. As the input string is searched from start, you might want to have the more propable values at the beginning.

Note that strchr does return a pointer to the matching char; just if you need that.

If you can group the values, e.g. "letters", "digits", etc., have a look at ctype.h.

If the values are variables, you can either copy them into an array of char before the compare (do not forget about the trminator!) or hold them in the array anyway: array[0] is c1, ... .

If all this is not possible, you are likely busted with strcpy. You could use this:

// assuming there are always the same variables used.
static const char * const ca[] = { &c1, &c2, ... };

char val;

for ( size_t i = 0 ; i < sizeof(ca) / sizeof(ca[0]) ; i++ ) {
    if ( *ca[i] == val ) {
        // match!
    }
}

You could pack that into a function with some decoration here and there.

Upvotes: 3

Related Questions