This is a cross-post from www.ModernesCpp.com.
At first, I have to apologize. Today, I wanted to continue my journey through the C++ Core Guidelines with the arithmetic expressions. In my seminar in this week, we had a long discussion about switch statements in C/C++ and how they become totally unmaintainable. Honestly, I’m not a fan of the switch statements and I have to say: there is life after the switch statements.
Before I write about the discussion and in particular one way to overcome the switch statement, here is at first my the plan for today.
- ES.78: Always end a non-empty case with a break
- ES.79: Use default to handle common cases (only)
Let’s dive directly into the switch statements.
ES.78: Always end a non-empty case with a break
I saw switch statements which more than hundred case labels. If you use non-empty cases without a break, the maintenance of this switch statements becomes a maintenance nightmare. Here is a first example of the guidelines:
switch (eventType) { case Information: update_status_bar(); break; case Warning: write_event_log(); // Bad – implicit fallthrough case Error: display_error_window(); break; }
Maybe, you overlooked it. The Warning case has no break statement; therefore, the Error case will automatically be executed.
Since C++17, we have a cure with the attribute [[fallthrough]]. Now, you can explicitly express your intent. [[fallthrough]] has to be on its own line, immediately before a case label and indicates that a fall through is intentional and should therefore not diagnose a compiler warning.
Here is a small example.
void f(int n) { void g(), h(), i(); switch (n) { case 1: case 2: g(); [[fallthrough]]; case 3: // no warning on fallthrough (1) h(); case 4: // compiler may warn on fallthrough (2) i(); [[fallthrough]]; // illformed, not before a case label (3) } }
The [[fallthrough]] attribute in line (1) suppresses a compiler warning. That will not hold for the line (2). The compiler may warn. Line (3) is ill-formed because no case label is following.
ES.79: Use default to handle common cases (only)
Here is my contrived example to make the rule clear.
// switch.cpp #include <iostream> enum class Message{ information, warning, error, fatal }; void writeMessage(){ std::cerr << “message” << std::endl; } void writeWarning(){ std::cerr << “warning” << std::endl; } void writeUnexpected(){ std::cerr << “unexpected” << std::endl; } void withDefault(Message mess){ switch(mess){ case Message::information: writeMessage(); break; case Message::warning: writeWarning(); break; default: writeUnexpected(); break; } } void withoutDefaultGood(Message mess){ switch(mess){ case Message::information: writeMessage(); break; case Message::warning: writeWarning(); break; default: // nothing can be done // (1)break; } } void withoutDefaultBad(Message mess){ switch(mess){ case Message::information: writeMessage(); break; case Message::warning: writeWarning(); break; } } int main(){ std::cout << std::endl; withDefault(Message::fatal); withoutDefaultGood(Message::information); withoutDefaultBad(Message::warning); std::cout << std::endl; }
The implementation of the functions withDefault and withoutDefaultGood are expressive enough. A maintainer of the function knows because of the comment (1) that there is no default case for this switch statement. Compare the function withoutDefaultGood and withoutDefaultBad from a maintenance point of view. Do you know, if the implementer of the function withoutDefaultBad forgot the default case or if the enumerator’s Message::error and Message::fatal were later added? At least, you have to study the source code or ask the original authors, if possible.
I mentioned already, that I had in my last seminar an intensive discussion about switch statements in C/C++. I forget to mention. It gave a Python seminar. Python has no switch statement. There is still a life after the switch statement in Python and maybe in C++. What is called in Python a dictionary, is typically coined hashtable, or unordered associative container in C++. We have it since C++11. The official name is std::unordered_map and it guarantees constant amortised time. This means independent of the size of std::unordered_map you get your answer at the same time.
My key takeaway is that an std::unordered_map is not only a data structure. An std::unordered_map is also a control structure for simulating a switch statement. This technique is called dispatch table. I already wrote a post about it: Functional in C++11 and C++14: Dispatch Table und Generic Lambdas.
To prove my point, I will implement the program switch.cpp one more by using an std::unoredered_map. For simplicity reason, I will use a global hash table.
// switchDict.cpp #include <functional> #include <iostream> #include <unordered_map> enum class Message{ information, warning, error, fatal }; void writeMessage(){ std::cerr << “message” << std::endl; } void writeWarning(){ std::cerr << “warning” << std::endl; } void writeUnexpected(){ std::cerr << “unexpected” << std::endl; } std::unordered_map<Message, std::function<void()>> mess2Func{ // (1) {Message::information, writeMessage}, {Message::warning, writeWarning} }; void withDefault(Message mess){ auto pair = mess2Func.find(mess); if (pair != mess2Func.end()){ pair->second(); } else{ writeUnexpected(); } } void withoutDefaultGood(Message mess){ auto pair = mess2Func.find(mess); if (pair != mess2Func.end()){ pair->second(); } else{ // Nothing can be done } } void withoutDefaultBad(Message mess){ auto pair = mess2Func.find(mess); if (pair != mess2Func.end()){ pair->second(); } } int main(){ std::cout << std::endl; withDefault(Message::fatal); withoutDefaultGood(Message::information); withoutDefaultBad(Message::warning); std::cout << std::endl; }
In line (1) is the std::unordered_map. I use it in the three functions withDefault, withoutDefaultGood, and withoutDefaultBad. The output of the program switchDict is exactly the same as the output of the program switch.
Of course, there are a few differences between the switch statement and the hash table. First, a hash table is a modifiable data structure; therefore, you can copy or modify it at runtime. Second, there is no fall through in the hashtable. You have to simulate it by adding the function to the key: mess2Func[Message::error] = writeWarning;. Now, the same action will happen for the key Message::warning and the key Message::error.
I will not argue about performance because depending on your use-case the dispatch table can be executed at compile time. For example, you can use constexpr functions.
What’s next
Sorry for the detour but the discussion in my seminar was too heavy. Next time, I will write finish the last rules to statements and start with the rules to arithmetic expressions.
