Comparing using an if () else if ()
chain is a linear search, offering O(n)
time complexity. For a large number of strings, depending on the use case, one option is using bsearch()
(binary search) to achieve O(log n)
time complexity.
Below is an example of how bsearch
can be used to perform a given action based on an input string similar to a switch
statement. This example finds a given mathematical function by name.
static int c(const void *const a, const void *const b) {
return strcmp(*(const char *const *)a, *(const char *const *)b);
}
static double (*func(const char *const str))(double) {
static const char *const s[] = {"abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "cbrt", "ceil", "cos", "cosh", "erf", "erfc", "exp", "expb", "floor", "gamma", "lgamma", "lb", "ln", "log", "round", "sin", "sinh", "sqrt", "tan", "tanh", "trunc"};
static double (*const f[])(double) = {fabs, acos, acosh, asin, asinh, atan, atanh, cbrt, ceil, cos, cosh, erf, erfc, exp, exp2, floor, tgamma, lgamma, log2, log, log10, round, sin, sinh, sqrt, tan, tanh, trunc};
const char *const *const r = bsearch(&str, s, sizeof(s)/sizeof(*s), sizeof(*s), c);
return r ? f[r-s] : NULL;
}