• Home
  • /
  • Blog
  • /
  • C++ Core Guidelines: To Switch or not to Switch, that is the Question

March 3, 2018

First, I have to apologize. Today, I wanted to continue my journey through the C++ Core Guidelines with arithmetic expressions. In my seminar this week, we had a long discussion about switch statements in C/C++ and how they become unmaintainable. Honestly, I’m not a fan of the switch statements, and I have to say: there is life after the switch statements.

 

hamlet 

Before I write about the discussion and, in particular, one way to overcome the switch statement, here is at first my plan for today.

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 a 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 fallthrough 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]]; // ill­formed, not before a case label (3)
  }
}

 

The [[fallthrough]] attribute in line (1) suppresses a compiler warning. That will not hold for 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 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 function implementer 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.

switch

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 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 had it since C++11. The official name is std::unordered_map, and it guarantees constant amortized time. This means independent of the size of std::unordered_map you get your answer at the same time.

My key takeaway is that a std::unordered_map is not only a data structure. A 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 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 reasons, 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 precisely the same as the output of the program switch.

switchDict

Of course, there are a few differences between the switch statement and the hash table. First, a hash table is a modifiable data structure; you can copy or modify it at runtime. Second, there is no fall-through in the hash table. You have to simulate it by adding the function to the key: mess2Func[Message::error] = writeWarning;. The same action will happen for the key Message::warning and the key Message::error.

I will not argue about performance because the dispatch table can be executed at compile time, depending on your use case. 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.

 

 

 

 

 

Leave a Reply


Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Related Posts