My last German post C++ Core Guidelines: To Switch or not to Switch, that is the Question got a lot of attention. To use a hash table instead of a switch statement seems to be a highly emotional topic. So I change my original plan. Today, I will present different kinds of control structures. I will start with the if and switch statements, continue with the hash table, and end with dynamic and static polymorphism. Additionally, I will mark a few remarks about performance and maintainability.
The classical control structure is the if statement; this is my starting point.
Here is the simple program that I will implement with different control structures.
The function writeMessage in line (1) displays the elapsed time in seconds (3) since the program’s start and a log message. It uses an enumeration (2) for the message severity. I use the start time (4) and the actual time (5) to calculate the elapsed time. As the name suggested, the std::steady_clock cannot be adjusted; therefore, it is the right choice for this measurement. The key part of the program is part of the function writeMessage (1), in which I decide which message should be displayed. In this case, I used if-else statements.
To make it right, I had to look up the syntax for the if-else statement.
Here is the output of the program:
I will skip the output for the remaining examples. Besides the numbers, it is always the same.
The following program is quite similar to the previous one. Only the implementation of the function writeMessage changed.
I will make it short. Let’s continue with the hash table.
For a more elaborate discussion of the switch statement and the hash table, read my last post: C++ Core Guidelines: To Switch or not to Switch, that is the Question.
Is this the end? No? In C++, we have dynamic and static polymorphism, as a few of my readers mentioned in their discussion. With the if-else or the switch statement, I used an enumerator to dispatch the correct case. The key of my hash table behaves similarly.
Dynamic or static polymorphism is different. Instead of an enumerator or a key for dispatching the right action, I use objects which decide autonomously at runtime (dynamic polymorphism) or compile-time (static polymorphism) what should be done.
Let’s continue with dynamic polymorphism.
Not, the decision logic is encoded in the type hierarchy.
The classes (1), (2), and (3) know what they have to display if used. The key idea is that the static type MessageSeverity differs from the dynamic type such as MessageInformation(4); therefore, the late binding will kick in, and the writeMessage methods (5), (6), and (7) of the dynamic types are used. Dynamic polymorphism requires a kind of indirection. You can use references (8) or pointers (9).
From a performance perspective, we can do better and make the dispatch at compile time.
Static polymorphism is often called CRTP. CRTP stands for the C++ idiom Curiously Recurring Template Pattern. Curiously because a class derives this technique from a class template instantiation using itself as a template argument.
In this case, all concrete classes (3), (4), and (5) derive from the base class MessageSeverity. The method writeMessage is a kind of interface that dispatches to the concrete implementations writeMessageImplementation. To make that happen, the object will be upcasted to the ConcreteMessage: static_cast<ConcreteMessage*>(this)->writeMessageImplementation();. This is the static dispatch at compile time; therefore, this technique is called static polymorphism.
It took me time to get used to it, but applying the static polymorphism in line (6) is quite easy. If the curiously recurring template pattern is still curious to you, I wrote an article about it: C++ is Lazy: CRTP
To end my comparison, let me compare these various techniques.
My simple comparison
Let’s first look at your preferred way to implement and maintain a control structure. Depending on your experience as a C programmer, the if or switch statements seem pretty natural to you. If you have an interpreter background, you may prefer the hash table. With an object orientation background, dynamic polymorphism is your preferred way to implement the control structure. Static polymorphism, also called CRTP, is quite unique; therefore, it will take some time to get comfortable with it. Afterward, it is quite a pattern you have to use.
I must mention the new context-sensitive identifiers override from the security perspective. It helps to express your intent to override a virtual method in your type hierarchy. If you make it wrong, the compiler will complain.
Now to the more interesting question. What are the performance differences? I will only provide a rough idea without numbers. If you have a long series of if statements, this will become quite expensive because many comparisons are involved. The dynamic polymorphism and the hash table will be faster and in the same ballpark because, in both cases, a pointer indirection is involved. The switch statement and the static polymorphism make their decision at compile time; therefore, they are the two fastest control structures.
I hope I’m done with the discussion of the different control structures; therefore, I will in my next post the last rules to statements and start with the rules for 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, Marco Parri Empoli, moon, and Philipp Lenk.
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|
|My special thanks to SHAVEDYAKS|
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,