{"id":5378,"date":"2018-01-27T08:25:28","date_gmt":"2018-01-27T08:25:28","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-rules-for-expressions\/"},"modified":"2023-06-26T11:57:53","modified_gmt":"2023-06-26T11:57:53","slug":"c-core-guidelines-rules-for-expressions","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-rules-for-expressions\/","title":{"rendered":"C++ Core Guidelines: Rules for Expressions"},"content":{"rendered":"<p>Today&#8217;s post is about expressions. You should avoid complicated expressions, know the precedence rules for arithmetic or logical expressions, and know the order of evaluation of expressions. The main reasons for undefined behavior are having the wrong precedence rules for expressions in mind or assuming an evaluation order for expressions that is just wrong or not guaranteed.&nbsp;I know that&#8217;s a lot to digest. Let&#8217;s start.<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5375\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/01\/Polynomial_expansion.png\" alt=\"Polynomial expansion\" width=\"400\" height=\"225\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/01\/Polynomial_expansion.png 1280w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/01\/Polynomial_expansion-300x169.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/01\/Polynomial_expansion-1024x576.png 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/01\/Polynomial_expansion-768x432.png 768w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/p>\n<p>Here are the four rules for today.<\/p>\n<ul style=\"margin-top: 0px; margin-bottom: 1rem; color: #515151; font-family: 'PT Sans', Helvetica, Arial, sans-serif; font-size: 20px; font-style: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; background-color: #ffffff;\">\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-complicated\" style=\"color: #268bd2; text-decoration: none;\">ES.40: Avoid complicated expressions<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-parens\" style=\"color: #268bd2; text-decoration: none;\">ES.41: If in doubt about operator precedence, parenthesize<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-order\" style=\"color: #268bd2; text-decoration: none;\">ES.43: Avoid expressions with undefined order of evaluation<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-order-fct\" style=\"color: #268bd2; text-decoration: none;\">ES.44: Don\u2019t depend on order of evaluation of function arguments<\/a><\/li>\n<\/ul>\n<p>The rules for the precedence and the evaluation are not as easy as it sounds. They even change with C++17; therefore, we should start simple.<\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-complicated\" style=\"color: #268bd2; text-decoration: none;\">ES.40: Avoid complicated expressions<\/a><\/h3>\n<p>What does complicated mean? Here is the original example of the guidelines:<\/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%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ bad: assignment hidden in subexpression                      (1)<\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">while<\/span> ((c <span style=\"color: #555555;\">=<\/span> getc()) <span style=\"color: #555555;\">!=<\/span> <span style=\"color: #555555;\">-<\/span><span style=\"color: #ff6600;\">1<\/span>)\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ bad: two non-local variables assigned in a sub-expressions   (1)<\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">while<\/span> ((cin <span style=\"color: #555555;\">&gt;&gt;<\/span> c1, cin <span style=\"color: #555555;\">&gt;&gt;<\/span> c2), c1 <span style=\"color: #555555;\">==<\/span> c2)\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ better, but possibly still too complicated                   (1)<\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">for<\/span> (<span style=\"color: #007788; font-weight: bold;\">char<\/span> c1, c2; cin <span style=\"color: #555555;\">&gt;&gt;<\/span> c1 <span style=\"color: #555555;\">&gt;&gt;<\/span> c2 <span style=\"color: #555555;\">&amp;&amp;<\/span> c1 <span style=\"color: #555555;\">==<\/span> c2;)\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ OK: if i and j are not aliased                               (2)<\/span>\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> x <span style=\"color: #555555;\">=<\/span> <span style=\"color: #555555;\">++<\/span>i <span style=\"color: #555555;\">+<\/span> <span style=\"color: #555555;\">++<\/span>j;                 \r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ OK: if i != j and i != k                                     (2)<\/span>\r\nv[i] <span style=\"color: #555555;\">=<\/span> v[j] <span style=\"color: #555555;\">+<\/span> v[k];\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ bad: multiple assignments \"hidden\" in subexpressions         (1)<\/span>\r\nx <span style=\"color: #555555;\">=<\/span> a <span style=\"color: #555555;\">+<\/span> (b <span style=\"color: #555555;\">=<\/span> f()) <span style=\"color: #555555;\">+<\/span> (c <span style=\"color: #555555;\">=<\/span> g()) <span style=\"color: #555555;\">*<\/span> <span style=\"color: #ff6600;\">7<\/span>;\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ bad: relies on commonly misunderstood precedence rules       (1)<\/span>\r\nx <span style=\"color: #555555;\">=<\/span> a <span style=\"color: #555555;\">&amp;<\/span> b <span style=\"color: #555555;\">+<\/span> c <span style=\"color: #555555;\">*<\/span> d <span style=\"color: #555555;\">&amp;&amp;<\/span> e <span style=\"color: #555555;\">^<\/span> f <span style=\"color: #555555;\">==<\/span> <span style=\"color: #ff6600;\">7<\/span>;\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ bad: undefined behavior                                      (3)<\/span>\r\nx <span style=\"color: #555555;\">=<\/span> x<span style=\"color: #555555;\">++<\/span> <span style=\"color: #555555;\">+<\/span> x<span style=\"color: #555555;\">++<\/span> <span style=\"color: #555555;\">+<\/span> <span style=\"color: #555555;\">++<\/span>x;\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>I added a few (numbers) to it. First, all expressions having a (1) are bad style and should not pass a code review. For example, do you know what is happening here:&nbsp;<span style=\"font-family: 'courier new', courier;\">x = a &amp; b + c * d &amp;&amp; e ^ f == 7;. <\/span>Of course, you have to look up the precedences of the operators. I will come to it in the following rule. The expression (2) may be acceptable if the conditions hold. i and j must be disjunct, and the indices i,j, and i,k must be pairwise disjunct.<\/p>\n<p>(3) is undefined behavior, because it is not defined which x will be evaluated first. Why? The argument is that the final semicolon &#8220;;&#8221; is a sequence point, and now we have the guarantee that all side effects from the previous evaluations in the sequence are complete.<\/p>\n<p>With C++17, the rules for operator precedence changed: left-to-right for expressions except for right-to-left in assignments. I will write about it in ES.43.<\/p>\n<\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-parens\" style=\"color: #268bd2; text-decoration: none;\">ES.41: If in doubt about operator precedence, parenthesize<\/a><\/h3>\n<p>On the one hand, the guidelines say: If you doubt operator precedence, use parenthesis (1). On the other hand, they state: You should know enough not to need parentheses here (2):<\/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%;\"><span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #007788; font-weight: bold;\">unsigned<\/span> <span style=\"color: #007788; font-weight: bold;\">int<\/span> flag <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">2<\/span>;\r\n<span style=\"color: #007788; font-weight: bold;\">unsigned<\/span> <span style=\"color: #007788; font-weight: bold;\">int<\/span> a <span style=\"color: #555555;\">=<\/span> flag;\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">if<\/span> (a <span style=\"color: #555555;\">&amp;<\/span> flag <span style=\"color: #555555;\">!=<\/span> <span style=\"color: #ff6600;\">0<\/span>)  <span style=\"color: #0099ff; font-style: italic;\">\/\/ bad: means a&amp;(flag != 0)         (1)<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">if<\/span> (a <span style=\"color: #555555;\">&lt;<\/span> <span style=\"color: #ff6600;\">0<\/span> <span style=\"color: #555555;\">||<\/span> a <span style=\"color: #555555;\">&lt;=<\/span> max) {  <span style=\"color: #0099ff; font-style: italic;\">\/\/ good: quite obvious        (2)<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Okay. For an expert, expression (1) may be obvious, but for a beginner, expression (2) may be a challenge.&nbsp;<\/p>\n<p>I have only two tips in mind according to the guidelines:<\/p>\n<ol>\n<li>If in doubt about precedence, use parentheses. Do not forget the beginners!<\/li>\n<li>Keep this precedence table from <a href=\"http:\/\/en.cppreference.com\/w\/cpp\/language\/operator_precedence\">cppreference.com<\/a> under your pillow.<\/li>\n<\/ol>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5376\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/01\/OperatorPrecedence.png\" alt=\"OperatorPrecedence\" width=\"600\" height=\"618\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/01\/OperatorPrecedence.png 717w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/01\/OperatorPrecedence-291x300.png 291w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<p>I will jump right to the rules ES.43 and ES.44 and write about the rule ES.42 in my next post. With C++17, the order of evaluation of expressions changed.<\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-order\" style=\"color: #268bd2; text-decoration: none;\">ES.43: Avoid expressions with undefined order of evaluation<\/a><\/h3>\n<p>In C++14, the following expression has undefined behavior.&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%;\">v[i] <span style=\"color: #555555;\">=<\/span> <span style=\"color: #555555;\">++<\/span>i;   <span style=\"color: #0099ff; font-style: italic;\">\/\/  the result is undefined<\/span>\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>This will not hold for C++17. With C++17, the order of evaluation of the last code snippet is right to left; therefore, the expression has well-defined behavior.<\/p>\n<p>Here are the additional guarantees we have with C++17:<\/p>\n<ol>\n<li>Postfix expressions are evaluated from left to right. This includes function calls and member selection expressions.<\/li>\n<li>Assignment expressions are evaluated from right to left. This includes compound assignments.<\/li>\n<li>Operands to shift operators are evaluated from left to right.&nbsp;<\/li>\n<\/ol>\n<p>This was the wording of the original <a href=\"http:\/\/www.open-std.org\/jtc1\/sc22\/wg21\/docs\/papers\/2016\/p0145r3.pdf\">proposal<\/a>. They also provided a few examples. Here are they:<\/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%;\">a.b\r\na<span style=\"color: #555555;\">-&gt;<\/span>b\r\na<span style=\"color: #555555;\">-&gt;*<\/span>b\r\na(b1, b2, b3)        <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\nb <span style=\"color: #aa0000; background-color: #ffaaaa;\">@<\/span><span style=\"color: #555555;\">=<\/span> a\r\na[b]\r\na <span style=\"color: #555555;\">&lt;&lt;<\/span> b\r\na <span style=\"color: #555555;\">&gt;&gt;<\/span> b\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>How should you read these examples? Quite simple. First, <span style=\"font-family: 'courier new', courier;\">a<\/span> will be evaluated, then <span style=\"font-family: 'courier new', courier;\">b<\/span>, c, and <span style=\"font-family: 'courier new', courier;\">d<\/span>.<\/p>\n<p>Expression (1) is a bit tricky. With C++17, we can only guarantee that the function is evaluated before its arguments, but the order of the evaluation of the arguments is still unspecified.<\/p>\n<p>I know the last sentence was not easy. Let&#8217;s elaborate a little bit more.<\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-order-fct\" style=\"color: #268bd2; text-decoration: none;\">ES.44: Don\u2019t depend on order of evaluation of function arguments<\/a><\/h3>\n<p>In the last years,&nbsp; I saw many errors because developers assumed that the order of the evaluation of function arguments is left to right. Wrong! You have no guarantees!<\/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: #009999;\">#include &lt;iostream&gt;<\/span>\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">func<\/span>(<span style=\"color: #007788; font-weight: bold;\">int<\/span> fir, <span style=\"color: #007788; font-weight: bold;\">int<\/span> sec){\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"(\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> fir <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\",\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> sec <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\")\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n}\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>(){\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> i <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>;\r\n    func(i<span style=\"color: #555555;\">++<\/span>, i<span style=\"color: #555555;\">++<\/span>);\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Here is my proof. The output from Gcc and clang differs:<\/p>\n<ul>\n<li>Gcc:<\/li>\n<\/ul>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" alignleft size-full wp-image-4858\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/08\/gcc.png\" alt=\"gcc\" style=\"margin-left: 50px; float: left;\" width=\"640\" height=\"395\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/08\/gcc.png 640w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/08\/gcc-300x185.png 300w\" sizes=\"auto, (max-width: 640px) 100vw, 640px\" \/><\/p>\n<p>&nbsp;<\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-magic\" style=\"color: #268bd2; text-decoration: none;\"><\/a><\/h3>\n<p>&nbsp;<\/p>\n<ul>\n<li>clang<\/li>\n<\/ul>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5377\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/01\/clang.png\" alt=\"clang\" style=\"margin-left: 50px;\" width=\"101\" height=\"76\" \/><\/p>\n<p>With C++17, this behavior didn&#8217;t change. The order of evaluation is unspecified. But at least the order of evaluating the following expressions is specified with C++17.<\/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%;\">f1()<span style=\"color: #555555;\">-&gt;<\/span>m(f2());          <span style=\"color: #0099ff; font-style: italic;\">\/\/ evaluation left to right  (1)<\/span>\r\ncout <span style=\"color: #555555;\">&lt;&lt;<\/span> f1() <span style=\"color: #555555;\">&lt;&lt;<\/span> f2();   <span style=\"color: #0099ff; font-style: italic;\">\/\/ evaluation left to right  (2)<\/span>\r\n\r\nf1() <span style=\"color: #555555;\">=<\/span> f(<span style=\"color: #ff6600;\">2<\/span>);            <span style=\"color: #0099ff; font-style: italic;\">\/\/ evaluation right to left  (3)<\/span>\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Here is the reason why:<\/p>\n<p>(1):&nbsp;Postfix expressions are evaluated from left to right. This includes function calls and member selection expressions.<\/p>\n<p>(2):&nbsp;Operands to shift operators are evaluated from left to right.<\/p>\n<p>(3): Assignment expressions are evaluated from right to left.<\/p>\n<p><strong>Only to remind you. With C++14, the last three expressions have undefined behavior.<\/strong><\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>Admittedly, this was quite a challenging post but a challenge you must overcome to become a good programmer. The main topic of my <a href=\"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-rules\">next post<\/a> will be about cast operations.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Today&#8217;s post is about expressions. You should avoid complicated expressions, know the precedence rules for arithmetic or logical expressions, and know the order of evaluation of expressions. The main reasons for undefined behavior are having the wrong precedence rules for expressions in mind or assuming an evaluation order for expressions that is just wrong or [&hellip;]<\/p>\n","protected":false},"author":21,"featured_media":5375,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[372],"tags":[495,496],"class_list":["post-5378","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-modern-c","tag-expressions","tag-pointers"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5378","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=5378"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5378\/revisions"}],"predecessor-version":[{"id":6841,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5378\/revisions\/6841"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5375"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5378"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5378"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5378"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}