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.
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.
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:
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.
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.
Here is my contrived example to make the rule clear.
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.
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.
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.
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.
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, 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, Rob North, Bhavith C Achar, and Marco Parri Empoli.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
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++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,