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 compar
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.