This shows you the differences between two versions of the page.
blog:2023:08:26:2023-08-26_-_handling_enums_in_c [2023/08/26 15:43] – created basz | blog:2023:08:26:2023-08-26_-_handling_enums_in_c [2023/08/26 15:50] (current) – tips and tricks on handlign enums in C++ basz | ||
---|---|---|---|
Line 73: | Line 73: | ||
===== handling some values ===== | ===== handling some values ===== | ||
+ | |||
+ | another common case where '' | ||
+ | |||
+ | <code cpp> | ||
+ | enum class State | ||
+ | { | ||
+ | Initializing, | ||
+ | Running, | ||
+ | InputError | ||
+ | }; | ||
+ | |||
+ | bool isOk(State s) | ||
+ | { | ||
+ | return s != State:: | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | looks good, all tests pass. however... you probably already know where it's going. ;) let's consider extending '' | ||
+ | |||
+ | |||
+ | <code cpp> | ||
+ | enum class State | ||
+ | { | ||
+ | Initializing, | ||
+ | Running, | ||
+ | InputError, | ||
+ | OutputError | ||
+ | }; | ||
+ | </ | ||
+ | |||
+ | ...and now '' | ||
+ | |||
+ | a better way of writing these kind of function is to list all '' | ||
+ | |||
+ | <code cpp> | ||
+ | #include < | ||
+ | // ... | ||
+ | bool isOk(State s) | ||
+ | { | ||
+ | switch(s) | ||
+ | { | ||
+ | case State:: | ||
+ | case State:: | ||
+ | return true; | ||
+ | case State:: | ||
+ | return false; | ||
+ | } | ||
+ | assert(!" | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | now, if states change, we get a proper error: | ||
+ | |||
+ | 4.cpp: In function ‘bool isOk(State)’: | ||
+ | 4.cpp:13:9: error: enumeration value ‘OutputError’ not handled in switch [-Werror=switch] | ||
+ | 13 | | ||
+ | | ^ | ||
+ | cc1plus: all warnings being treated as errors | ||
+ | |||
+ | so we know we need to fix it: | ||
+ | |||
+ | <code cpp> | ||
+ | #include < | ||
+ | // ... | ||
+ | bool isOk(State s) | ||
+ | { | ||
+ | switch(s) | ||
+ | { | ||
+ | case State:: | ||
+ | case State:: | ||
+ | return true; | ||
+ | case State:: | ||
+ | case State:: | ||
+ | return false; | ||
+ | } | ||
+ | assert(!" | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | while writing this kind of functions using '' |