{"id":5754,"date":"2019-08-08T16:33:26","date_gmt":"2019-08-08T16:33:26","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-non-rules-and-myths\/"},"modified":"2019-08-08T16:33:26","modified_gmt":"2019-08-08T16:33:26","slug":"c-core-guidelines-non-rules-and-myths","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-non-rules-and-myths\/","title":{"rendered":"C++ Core Guidelines: Non-Rules and Myths"},"content":{"rendered":"<p>Of course, you already know many non-rules and myths about C++. Non-rules and myths which we have to argue against when we use modern C++. The supporting section of the C++ core guidelines addresses the most resistant ones but also provides alternatives.<span style=\"font-family: Arial;\"><\/span><\/p>\n<p><!--more--><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5752\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2019\/08\/dragons-head-310697_1280.png\" alt=\"dragons head 310697 1280\" width=\"500\" height=\"458\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2019\/08\/dragons-head-310697_1280.png 1280w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2019\/08\/dragons-head-310697_1280-300x275.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2019\/08\/dragons-head-310697_1280-1024x938.png 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2019\/08\/dragons-head-310697_1280-768x703.png 768w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/p>\n<p>Here are the rules for today.<\/p>\n<ul>\n<li><a href=\"https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rnr-top\">NR.1: Don\u2019t: All declarations should be at the top of a function<\/a><\/li>\n<li><a href=\"https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rnr-single-return\">NR.2: Don\u2019t: Have only a single <code class=\"highlighter-rouge no-highlight\">return<\/code>-statement in a function<\/a><\/li>\n<li><a href=\"https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rnr-no-exceptions\">NR.3: Don\u2019t: Don\u2019t use exceptions<\/a><\/li>\n<li><a href=\"https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rnr-lots-of-files\">NR.4: Don\u2019t: Place each class declaration in its own source file<\/a><\/li>\n<\/ul>\n<p>Many programmers apply the first rules.<\/p>\n<h2><a href=\"https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rnr-top\">NR.1: Don\u2019t: All declarations should be at the top of a function<\/a><\/h2>\n<p>This rule is a relict of old programming languages that don&#8217;t allow the initialization of variables and constants after a statement. The result of a significant distance of the variable declaration and their usage is often that you forget to initialize the variable. Exactly this happens in the example of the C++ core guidelines:<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">use<\/span>(<span style=\"color: #007788; font-weight: bold;\">int<\/span> x)\r\n{  \r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> i;\r\n    <span style=\"color: #007788; font-weight: bold;\">char<\/span> c;\r\n    <span style=\"color: #007788; font-weight: bold;\">double<\/span> d;\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ... some stuff ...<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (x <span style=\"color: #555555;\">&lt;<\/span> i) {\r\n        <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n       i <span style=\"color: #555555;\">=<\/span> f(x, d);\r\n    }\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (i <span style=\"color: #555555;\">&lt;<\/span> x) {\r\n        <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n        i <span style=\"color: #555555;\">=<\/span> g(x, c);\r\n    }\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> ;\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>I assume you already found the issue in this code snippet. The variable<span style=\"font-family: Courier New, Courier, monospace;\"> i (<\/span>the same holds for<span style=\"font-family: Courier New, Courier, monospace;\"> c <\/span>and<span style=\"font-family: Courier New, Courier, monospace;\"> d) <\/span>is not initialized because it is a built-in variable used in a local scope. Therefore, the program has undefined behavior. If it were a user-defined type such as <span style=\"font-family: Courier New, Courier, monospace;\">std::string,<\/span> all would be fine. So, what should you do:<\/p>\n<ul>\n<li>Place the declaration of i directly before its first usage.<\/li>\n<li>Always initialize a variable such as<span style=\"font-family: Courier New, Courier, monospace;\"> int i{}<\/span>, or better, use <span style=\"font-family: Courier New, Courier, monospace;\">auto<\/span>. The compiler can not guess from a declaration such as <span style=\"font-family: Courier New, Courier, monospace;\">auto i;<\/span> the type of<span style=\"font-family: Courier New, Courier, monospace;\"> i <\/span>and will, therefore, reject the program. To put it the other way around <span style=\"font-family: courier new, courier;\">auto<\/span> forces you to initialize your variables.<\/li>\n<\/ul>\n<p>I also know the next rule from discussions.<\/p>\n<\/p>\n<h2><a href=\"https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rnr-single-return\">NR.2: Don\u2019t: Have only a single <code class=\"highlighter-rouge no-highlight\">return<\/code>-statement in a function<\/a><\/h2>\n<p>When you follow this rule, you implicitly apply the first non-rule.<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">template<\/span><span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">T<\/span><span style=\"color: #555555;\">&gt;<\/span>\r\nstd<span style=\"color: #555555;\">::<\/span>string sign(T x)    <span style=\"color: #0099ff; font-style: italic;\">\/\/ bad<\/span>\r\n{\r\n    std<span style=\"color: #555555;\">::<\/span>string res;   \r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (x <span style=\"color: #555555;\">&lt;<\/span> <span style=\"color: #ff6600;\">0<\/span>)\r\n        res <span style=\"color: #555555;\">=<\/span> <span style=\"color: #cc3300;\">\"negative\"<\/span>;\r\n    <span style=\"color: #006699; font-weight: bold;\">else<\/span> <span style=\"color: #006699; font-weight: bold;\">if<\/span> (x <span style=\"color: #555555;\">&gt;<\/span> <span style=\"color: #ff6600;\">0<\/span>)\r\n        res <span style=\"color: #555555;\">=<\/span> <span style=\"color: #cc3300;\">\"positive\"<\/span>;\r\n    <span style=\"color: #006699; font-weight: bold;\">else<\/span>\r\n        res <span style=\"color: #555555;\">=<\/span> <span style=\"color: #cc3300;\">\"zero\"<\/span>;\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> res;\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Using more return statements makes the code easier to read and also faster.<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">template<\/span><span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">T<\/span><span style=\"color: #555555;\">&gt;<\/span><span style=\"color: #0099ff; font-style: italic;\"><\/span>\r\nstd::string sign(T x)\r\n{\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (x <span style=\"color: #555555;\">&lt;<\/span> <span style=\"color: #ff6600;\">0<\/span>)\r\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #cc3300;\">\"negative\"<\/span>;\r\n    <span style=\"color: #006699; font-weight: bold;\">else<\/span> <span style=\"color: #006699; font-weight: bold;\">if<\/span> (x <span style=\"color: #555555;\">&gt;<\/span> <span style=\"color: #ff6600;\">0<\/span>)\r\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #cc3300;\">\"positive\"<\/span>;\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #cc3300;\">\"zero\"<\/span>;\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Okay. What happens if I use automatic return type deduction return different types?<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ differentReturnTypes.cpp<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">template<\/span> <span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">typename<\/span> T<span style=\"color: #555555;\">&gt;<\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">auto<\/span> getValue(T x){\r\n  <span style=\"color: #006699; font-weight: bold;\">if<\/span> (x <span style=\"color: #555555;\">&lt;<\/span> <span style=\"color: #ff6600;\">0<\/span>)          <span style=\"color: #0099ff; font-style: italic;\">\/\/ int<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #555555;\">-<\/span><span style=\"color: #ff6600;\">1<\/span>;\r\n  <span style=\"color: #006699; font-weight: bold;\">else<\/span> <span style=\"color: #006699; font-weight: bold;\">if<\/span> (x <span style=\"color: #555555;\">&gt;<\/span> <span style=\"color: #ff6600;\">0<\/span>)\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #ff6600;\">1.0<\/span>;       <span style=\"color: #0099ff; font-style: italic;\">\/\/ double<\/span>\r\n  <span style=\"color: #006699; font-weight: bold;\">else<\/span> <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #ff6600;\">0.0f<\/span>;   <span style=\"color: #0099ff; font-style: italic;\">\/\/ float<\/span>\r\n}\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> main(){\r\n\r\n    getValue(<span style=\"color: #ff6600;\">5.5<\/span>);\r\n \r\n}  \r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>As expected, just an error:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5753\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2019\/08\/differentReturnTypes.PNG\" alt=\"differentReturnTypes\" width=\"600\" height=\"159\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2019\/08\/differentReturnTypes.PNG 3699w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2019\/08\/differentReturnTypes-300x79.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2019\/08\/differentReturnTypes-1024x271.png 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2019\/08\/differentReturnTypes-768x203.png 768w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2019\/08\/differentReturnTypes-1536x406.png 1536w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2019\/08\/differentReturnTypes-2048x541.png 2048w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<p>Probably, the next non-rule is the most controversial one.<\/p>\n<h2><a href=\"https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rnr-no-exceptions\">NR.3: Don\u2019t: Don\u2019t use exceptions<\/a><\/h2>\n<p>First, the guideline states the main reasons against exceptions:<\/p>\n<ol>\n<li>exceptions are inefficient<\/li>\n<li>exceptions lead to leaks and errors<\/li>\n<li>exception performance is not predictable<\/li>\n<\/ol>\n<p>The guidelines have profound answers to these statements.<\/p>\n<p>1. Often, the efficiency of exception handling is compared to a program that just terminated or displays the error code. Often the exception-handling implementation is poor. Of course, a comparison makes in such cases no sense. I want to explicitly mention the paper <a href=\"http:\/\/www.open-std.org\/jtc1\/sc22\/wg21\/docs\/TR18015.pdf\">Technical Report on C++ Performance<\/a> (TR18015.pdf), which presents two typical ways to implement exceptions:<\/p>\n<ol>\n<li>The code approach, where code is associated with each try-block<\/li>\n<li>The &#8220;table&#8221; approach, which uses compiler-generated static tables<\/li>\n<\/ol>\n<p>Roughly said, the &#8220;code&#8221; approach has the downside that even when no exceptions are thrown, the bookkeeping of the exception handling stack must be performed, and, therefore, code unrelated to error handling slows down. This downside does not hold for the &#8220;table&#8221; approach because it introduces no stack or runtime costs when no exception is thrown. In contrast, the &#8220;table&#8221; approach seems more complicated, and the static table can get quite big.<\/p>\n<p>2. I have nothing to add to point 2. Exceptions can not be blamed for a missing resource management strategy.<\/p>\n<p>3. If you have hard-realtime guarantees to fulfill so that a too-late answer is a wrong answer, an exception implementation based on the &#8220;table&#8221; approach will not&nbsp; &#8211; as we saw&nbsp; &#8211; affect the program&#8217;s run-time in the excellent case. Honestly, even if you have a hard-realtime system, this hard-realtime restriction typically only holds for a small part of your system.&nbsp;<\/p>\n<p>Instead of arguing against the non-rules, here are the reasons for using exceptions:<\/p>\n<p>Exceptions<\/p>\n<ul>\n<li>differentiate between an erroneous return and an ordinary return.<\/li>\n<li>cannot be forgotten or ignored.<\/li>\n<li>can be used systematically.<\/li>\n<\/ul>\n<p>Let me add an anecdote I once faced in legacy code. The system used error codes to signal the success or failure of a function. Okay, they checked the error codes. This was fine. But due to the error codes, the functions didn&#8217;t use return values. The consequence was that the functions operated on global variables and had no parameters because they used the global variables anyway. The end of the story was that the system was not maintainable or testable, and my job was it to refactor it.&nbsp;<\/p>\n<p>The typical wrong usage of exception handling I see is the following one. You catch every exception in every function. In the end, you get unmaintainable code with a spaghetti-like structure. Exceptions are not a tool to make a fast fix but should be part of the overall system architecture. Imagine you design an input sub-system. You must also document and test the exceptions that can occur. Exceptions are an essential part of the non-functional channel and, therefore, part of the contract you provide to your sub-system user. It would help to have a clear boundary between the application and the sub-system. The result may be that the sub-system translates the obscure exceptions into simpler ones so the application can react. Translating an exception means that you catch obscure exceptions in the sub-system and re-throw an easy-do-digest exception:<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\">try{\r\n     <span style=\"color: #0099ff; font-style: italic;\">\/\/ code, that may throw an obscure exception<\/span>\r\n  }   \r\n  <span style=\"color: #006699; font-weight: bold;\">catch<\/span> (ObscureException18<span style=\"color: #555555;\">&amp;<\/span> ob){\r\n      <span style=\"color: #006699; font-weight: bold;\">throw<\/span> InputSubsystemError(<span style=\"color: #cc3300;\">\"File has wrong permissions!\"<\/span>);\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The result of such a system architecture including the non-functional channel (exceptions) is that you can test the sub-system in isolation, you can test the integration of the sub-system into the application, and you can test the system (application).&nbsp;<\/p>\n<p>The last myth for today is relatively easy to spot.<\/p>\n<h2><a href=\"https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rnr-lots-of-files\">NR.4: Don\u2019t: Place each class declaration in its own source file<\/a><\/h2>\n<p>The correct way to structure your code is not to use files but to use namespaces. Using a file for each class declaration results in many files, making your program more complicated to manage and slower to compile.<\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>You can be sure. The C++ core guidelines and I&#8217;m not done with the non-rules and myths of C++. I will continue in my <a href=\"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-more-non-rules-and-myths\">next post<\/a>. Afterward, when you encounter the non-rules and myths, you should know how to demystify them.<\/p>\n<p>&nbsp;<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Of course, you already know many non-rules and myths about C++. Non-rules and myths which we have to argue against when we use modern C++. The supporting section of the C++ core guidelines addresses the most resistant ones but also provides alternatives.<\/p>\n","protected":false},"author":21,"featured_media":5752,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[372],"tags":[],"class_list":["post-5754","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-modern-c"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5754","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/comments?post=5754"}],"version-history":[{"count":0,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5754\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5752"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5754"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5754"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5754"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}