C++ Core Guidelines: To Switch or not to Switch, that is the Question

Contents[Show]

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.

 

hamlet 

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.

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]]; // ill­formed, 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.

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Stay informed about my mentoring programs.

 

 

Subscribe via E-Mail.

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 an 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.

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 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.

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; therefore, 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;. 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.

 

 

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Dominik Vošček, and Rob North.

 

Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

My special thanks to Tipi.build tipi.build logo

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

  • C++ - The Core Language
  • C++ - The Standard Library
  • C++ - Compact
  • C++11 and C++14
  • Concurrency with Modern C++
  • Design Pattern and Architectural Pattern with C++
  • Embedded Programming with Modern C++
  • Generic Programming (Templates) with C++

New

  • Clean Code with Modern C++
  • C++20

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

 

 

Mentoring

Stay Informed about my Mentoring

 

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

All tags

Blog archive

Source Code

Visitors

Today 1118

Yesterday 4552

Week 42232

Month 186403

All 11667557

Currently are 119 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments