{"id":5487,"date":"2018-08-17T11:12:57","date_gmt":"2018-08-17T11:12:57","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/c-core-gudelines-goto-considered-evil\/"},"modified":"2023-06-26T11:46:02","modified_gmt":"2023-06-26T11:46:02","slug":"c-core-gudelines-goto-considered-evil","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/c-core-gudelines-goto-considered-evil\/","title":{"rendered":"C++ Core Gudelines: goto considered Evil"},"content":{"rendered":"<p>If you can&#8217;t throw an exception and can&#8217;t use <code>final_action<\/code> (<code>finally<\/code>) from the <a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#S-gsl\">guideline support library<\/a>, you have a problem. Exceptional states require exceptional actions: <code>goto.<\/code> Really?<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5486\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/08\/firefighters-1147795_1280.jpg\" alt=\"firefighters 1147795 1280\" width=\"500\" height=\"332\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/08\/firefighters-1147795_1280.jpg 1280w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/08\/firefighters-1147795_1280-300x199.jpg 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/08\/firefighters-1147795_1280-1024x679.jpg 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/08\/firefighters-1147795_1280-768x509.jpg 768w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/p>\n<p>I was pretty surprised to read the guidelines about <code>goto exit;<\/code> the final rescue. Here are the remaining rules for error handling in the C++ core guidelines.<\/p>\n<ul>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re-no-throw-raii\">E.25: If you can\u2019t throw exceptions, simulate RAII for resource management<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re-no-throw-crash\">E.26: If you can\u2019t throw exceptions, consider failing fast<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re-no-throw-codes\">E.27: If you can\u2019t throw exceptions, use error codes systematically<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re-specifications\">E.30: Don\u2019t use exception specifications<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re_catch\">E.31: Properly order your <code class=\"highlighter-rouge no-highlight\">catch<\/code>-clauses<\/a><\/li>\n<\/ul>\n<p>The first three rules are quite related; therefore, I will write about them together.<\/p>\n<h2><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re-no-throw-raii\">E5: If you can\u2019t throw exceptions, simulate RAII for resource management<\/a>, <a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re-no-throw-crash\">E.26: If you can\u2019t throw exceptions, consider failing fast<\/a>, and <a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re-no-throw-codes\">E.27: If you can\u2019t throw exceptions, use error codes systematically<\/a><\/h2>\n<p>The idea of RAII is quite simple. If you have to take care of a resource, put the resource into a class<code>.<\/code> Use the class&#8217;s constructor for the initialization and the destructor for the destruction of the resource. When you create a local instance of the class&nbsp;on the stack, the C++ runtime takes care of the resource, and you are done. For more information on RAII, read my previous post <a href=\"https:\/\/www.modernescpp.com\/index.php\/garbage-collectio-no-thanks\">Garbage Collection &#8211; No Thanks<\/a>.<\/p>\n<p>What does it mean to simulate RAII for resource management? Imagine you have a function <code>func<\/code> which exists with an exception if G<code>adget<\/code> can&#8217;t be created.<\/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;\">void<\/span> <span style=\"color: #cc00ff;\">func<\/span>(zstring arg)\r\n{\r\n    Gadget g {arg};\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>If you can not throw an exception, you should simulate RAII by adding a <code>valid<\/code> method to <code>Gadget.<\/code><\/p>\n<p>&nbsp;<\/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%;\">error_indicator <span style=\"color: #cc00ff;\">func<\/span>(zstring arg)\r\n{\r\n    Gadget g {arg};\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (<span style=\"color: #555555;\">!<\/span>g.valid()) <span style=\"color: #006699; font-weight: bold;\">return<\/span> gadget_construction_error;\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #ff6600;\">0<\/span>;   <span style=\"color: #0099ff; font-style: italic;\">\/\/ zero indicates \"good\"<\/span>\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>In this case, the caller has to test the return value.<\/p>\n<p>Rules E.26 is straightforward. If there is no way to recover from an error such as memory exhaustion, fail fast. If you can&#8217;t throw an exception call <a href=\"https:\/\/en.cppreference.com\/w\/cpp\/utility\/program\/abort\"><code>std::abort<\/code><\/a> that causes abnormal program termination.<\/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;\">void<\/span> <span style=\"color: #cc00ff;\">f<\/span>(<span style=\"color: #007788; font-weight: bold;\">int<\/span> n)\r\n{\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n    p <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">static_cast<\/span><span style=\"color: #555555;\">&lt;<\/span>X<span style=\"color: #555555;\">*&gt;<\/span>(malloc(n, X));\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (<span style=\"color: #555555;\">!<\/span>p) abort();     <span style=\"color: #0099ff; font-style: italic;\">\/\/ abort if memory is exhausted<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p><code>std::abort<\/code> will only cause an abnormal program termination if you don&#8217;t install a signal handler that catches the signal <span class=\"t-lc\"><a href=\"https:\/\/en.cppreference.com\/w\/cpp\/utility\/program\/SIG_types\" title=\"cpp\/utility\/program\/SIG types\">SIGABRT. <\/a><\/span><\/p>\n<p>The function f behaves such as the following function:<\/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;\">void<\/span> <span style=\"color: #cc00ff;\">f<\/span>(<span style=\"color: #007788; font-weight: bold;\">int<\/span> n)\r\n{\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n    p <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> X[n];    <span style=\"color: #0099ff; font-style: italic;\">\/\/ throw if memory is exhausted (by default, terminate)<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Now, I will write about the non-word&nbsp;<code>goto <\/code>in rule E.27.<\/p>\n<p>In case of an error, you have a few issues to solve according to the guidelines:<\/p>\n<ol>\n<li>how do you transmit an error indicator from out of a function?<\/li>\n<li>how do you release all resources from a function before doing an error exit?<\/li>\n<li>What do you use as an error indicator?<\/li>\n<\/ol>\n<p>In general, your function should have two return values. The value and the error indicator, therefore, <code>std::pair<\/code> is a good fit. Releasing the resources may quickly become a maintenance nightmare, even if you encapsulate the cleanup code in functions.<\/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%;\">std<span style=\"color: #555555;\">::<\/span>pair<span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #007788; font-weight: bold;\">int<\/span>, error_indicator<span style=\"color: #555555;\">&gt;<\/span> user()\r\n{\r\n    Gadget g1 <span style=\"color: #555555;\">=<\/span> make_gadget(<span style=\"color: #ff6600;\">17<\/span>);\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (<span style=\"color: #555555;\">!<\/span>g1.valid()) {\r\n            <span style=\"color: #006699; font-weight: bold;\">return<\/span> {<span style=\"color: #ff6600;\">0<\/span>, g1_error};\r\n    }\r\n\r\n    Gadget g2 <span style=\"color: #555555;\">=<\/span> make_gadget(<span style=\"color: #ff6600;\">17<\/span>);\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (<span style=\"color: #555555;\">!<\/span>g2.valid()) {\r\n            cleanup(g1);\r\n            <span style=\"color: #006699; font-weight: bold;\">return<\/span> {<span style=\"color: #ff6600;\">0<\/span>, g2_error};\r\n    }\r\n\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (all_foobar(g1, g2)) {\r\n        cleanup(g1);\r\n        cleanup(g2);\r\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> {<span style=\"color: #ff6600;\">0<\/span>, foobar_error};\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n\r\n    cleanup(g1);\r\n    cleanup(g2);\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> {res, <span style=\"color: #ff6600;\">0<\/span>};\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Okay, that seems to be correct! Or?<\/p>\n<p>Do you know what <strong>DRY<\/strong> stands for? <strong>D<\/strong>on&#8217;t <strong>R<\/strong>epeat <strong>Y<\/strong>ourself. Although the cleanup code is encapsulated into functions the code has a smell of code repetition because the cleanup functions are invoked in various places. How can we get rid of repetition? Just put the cleanup code at the end of the function and jump to it.<\/p>\n<p>&nbsp;<\/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%;\">std<span style=\"color: #555555;\">::<\/span>pair<span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #007788; font-weight: bold;\">int<\/span>, error_indicator<span style=\"color: #555555;\">&gt;<\/span> user()\r\n{\r\n    error_indicator err <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>;\r\n\r\n    Gadget g1 <span style=\"color: #555555;\">=<\/span> make_gadget(<span style=\"color: #ff6600;\">17<\/span>);\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (<span style=\"color: #555555;\">!<\/span>g1.valid()) {\r\n            err <span style=\"color: #555555;\">=<\/span> g1_error;          <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n            <span style=\"color: #006699; font-weight: bold;\">goto<\/span> exit;\r\n    }\r\n\r\n    Gadget g2 <span style=\"color: #555555;\">=<\/span> make_gadget(<span style=\"color: #ff6600;\">17<\/span>);\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (<span style=\"color: #555555;\">!<\/span>g2.valid()) {\r\n            err <span style=\"color: #555555;\">=<\/span> g2_error;          <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n            <span style=\"color: #006699; font-weight: bold;\">goto<\/span> exit;\r\n    }\r\n\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (all_foobar(g1, g2)) {\r\n        err <span style=\"color: #555555;\">=<\/span> foobar_error;          <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n        <span style=\"color: #006699; font-weight: bold;\">goto<\/span> exit;\r\n    }\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n\r\n<span style=\"color: #9999ff;\">exit:<\/span>\r\n  <span style=\"color: #006699; font-weight: bold;\">if<\/span> (g1.valid()) cleanup(g1);\r\n  <span style=\"color: #006699; font-weight: bold;\">if<\/span> (g2.valid()) cleanup(g2);\r\n  <span style=\"color: #006699; font-weight: bold;\">return<\/span> {res, err};\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Admitted, with the help of <code>goto<\/code> the overall structure of the function is quite clear. Just the error indicator (1) is set in case of an error. Exceptional states require exceptional actions.&nbsp;<\/p>\n<\/p>\n<h2><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re-specifications\">E.30: Don\u2019t use exception specifications<\/a><\/h2>\n<p>First, here is an example of an exception specification:<\/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> arg)\r\n    <span style=\"color: #006699; font-weight: bold;\">throw<\/span>(X, Y)\r\n{\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">auto<\/span> x <span style=\"color: #555555;\">=<\/span> f(arg);\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>This means that the function used may allow throwing an exception of type <code>X<\/code>, or <code>Y<\/code>. If a different exception is thrown, <code>std::terminate<\/code> it is called.<\/p>\n<p>Dynamic exception specification with argument <code>throw(X, Y<\/code>) and without argument <code>throw()<\/code>&nbsp;is deprecated since C++11. Dynamic exception specification with arguments is removed with C++17, but dynamic exception specification without arguments will be removed with C++20. th<code>row()<\/code> is equivalent to <code>noexcept.<\/code> Here are more details: <a href=\"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-the-noexcept-specifier-and-operator\">C++ Core Guidelines: The noexcept Specifier and Operator.<\/a>&nbsp;<\/p>\n<p>If you don&#8217;t know the last rule, it can be astonishing.<\/p>\n<h2><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re_catch\">E.31: Properly order your <code class=\"highlighter-rouge no-highlight\">catch<\/code>-clauses<\/a><\/h2>\n<p>An exception is cached according to the best-fit strategy. This means the first exception handler that fits an actual exception is used. This is why you should structure your exception handler from specific to general. If not, your specific exception handler may never be invoked. In the following example, the <code>DivisionByZeroException<\/code> is derived from <code>std::exception.<\/code><\/p>\n<p>&nbsp;<\/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;\">\/\/ throw an exception   (1) <\/span>\r\n}\r\n<span style=\"color: #006699; font-weight: bold;\">catch<\/span>(<span style=\"color: #006699; font-weight: bold;\">const<\/span> DivisionByZeroException<span style=\"color: #555555;\">&amp;<\/span> ex){ .... } <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2) <\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">catch<\/span>(<span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>exception<span style=\"color: #555555;\">&amp;<\/span> ex{ .... }           <span style=\"color: #0099ff; font-style: italic;\">\/\/ (3) <\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">catch<\/span>(...){ .... }                               <span style=\"color: #0099ff; font-style: italic;\">\/\/ (4) <\/span>\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>In this case, the <code>DivisionByZeroException<\/code> (2) is used first for handling the exception thrown in line (1). If the specific handler does not work, all exceptions derived from <code>std::exception<\/code> (3) are caught in the following line. The last exception handler has an ellipsis (4) and can, therefore, catch all exceptions.&nbsp;<\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>As promised, I will write in the next post about the five rules for constants and immutability in C++.<\/p>\n<h2>&nbsp;<\/h2><\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you can&#8217;t throw an exception and can&#8217;t use final_action (finally) from the guideline support library, you have a problem. Exceptional states require exceptional actions: goto. Really?<\/p>\n","protected":false},"author":21,"featured_media":5486,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[372],"tags":[478,479],"class_list":["post-5487","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-modern-c","tag-error-handling","tag-exceptions"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5487","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=5487"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5487\/revisions"}],"predecessor-version":[{"id":6815,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5487\/revisions\/6815"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5486"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5487"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5487"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5487"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}