Compact way to write if(..) statement with many equalities

Viewed 5136

Is there a better way to write code like this:

if (var == "first case" or var == "second case" or var == "third case" or ...)

In Python I can write:

if var in ("first case", "second case", "third case", ...)

which also gives me the opportunity to easily pass the list of good options:

good_values = "first case", "second case", "third case"
if var in good_values

This is just an example: the type of var may be different from a string, but I am only interested in alternative (or) comparisons (==). var may be non-const, while the list of options is known at compile time.

Pro bonus:

  • laziness of or
  • compile time loop unrolling
  • easy to extend to other operators than ==
9 Answers
Related