    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: BRACKETS OFF!</title>
        <link>https://members.accu.org/index.php/journals/1249</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">CVu Journal Vol 15, #6 - Dec 2003 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c105/">156</a>
                    (7)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c105-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c105+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;BRACKETS OFF!</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 03 December 2003 13:16:01 +00:00 or Wed, 03 December 2003 13:16:01 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a></h2>
</div>
<p>The mathematical formula:</p>
<pre class="programlisting">
              v = u + at
</pre>
<p>calculates the speed, <tt class="varname">v</tt>, of an object,
with initial speed <tt class="varname">u</tt> and constant
acceleration <tt class="varname">a</tt>, after time <tt class=
"varname">t</tt>. Placing the &quot;<tt class="varname">a</tt>&quot; next to
the &quot;<tt class="varname">t</tt>&quot; is a convenient shorthand for
&quot;multiply <tt class="varname">a</tt> by <tt class=
"varname">t</tt>&quot;, which also makes it apparent that the
multiplication must be done before the addition.</p>
<p>When the same formula is written in C, the multiplication
operator needs explicit representation:</p>
<pre class="programlisting">
Example 0)    v = u + a * t
</pre>
<p>The layout of this expression no longer makes it clear that the
multiplication should be done before the addition, so a programmer
might choose to parenthesise:</p>
<pre class="programlisting">
              v = u + (a * t)
</pre>
<p>Are these parentheses required to guarantee correct evaluation
of <tt class="varname">v</tt>? If not, should they be included
anyway, to help convey the meaning of the expression? How can
coding standards help with such choices?</p>
<p>This article aims to answer these questions. It first presents
some examples of the operator precedence and associativity rules in
action, then offers some guidelines on when to parenthesise
expressions, and finally argues that these guidelines should be
replaced by a single rule.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e67" id="d0e67"></a>More
Examples</h2>
</div>
<pre class="programlisting">
Example 1)    x = 8 - 4 - 2
Example 2)    r = h &lt;&lt; 4 + 1
Example 3)    str += ((errors == 0) ? 'succeeded&quot; : &quot;failed&quot;)
Example 4)    *utf++ = 0x80 | ucs &gt;&gt; 6 &amp; 0x6f
</pre>
<p>The expression presented in Example 0 contains three operators:
assignment, addition and multiplication. These operators - indeed
all operators - follow a strict precedence which defines the order
of evaluation. Since multiplication has higher precedence than
addition, which in turn has higher precedence than assigment, the
expression is equivalent to:</p>
<pre class="programlisting">
              v = (u + (a * t))
</pre>
<p>This means the compiler can be trusted with the expression as
first presented. No parentheses are required. Good, the language
does what we expect.</p>
<p>In Example 1, subtraction binds more tightly (i.e. has higher
precedence than) assignment, so the subtractions are performed
first. Since all the arithmetic operators associate left to right,
the expression is equivalent to:</p>
<pre class="programlisting">
              x = ((8 - 4) - 2)
</pre>
<p>In Example 2, arithmetic operators bind more tightly than shift
operators, so the expression is equivalent to:</p>
<pre class="programlisting">
              r = (h &lt;&lt; (4 + 1))
</pre>
<p>Why did the programmer not write r = h &lt;&lt; 5 ? Probably
because he really meant:</p>
<pre class="programlisting">
              r = (h &lt;&lt; 4) + 1
</pre>
<p>but bit shifting (like, say, finding the address of something,
or subscripting an array) somehow seems closer to the machine and
feels as if it ought to be of higher precedence than addition, so
the crucial parentheses were missed<sup>[<a name="d0e92" href=
"#ftn.d0e92" id="d0e92">1</a>]</sup>.</p>
<p>In example 3, the parentheses are unneccessary, since the
comparison operators bind more tightly than the conditional
operator, which in turn binds more tightly than the assignment
operators. Do the parentheses help you understand the meaning of
this expression? Would you have left them out - and if so, would
one of your team-mates have complained?</p>
<p>How should the fourth example be parenthesised, to make its
meaning clear? It is equivalent to:</p>
<pre class="programlisting">
              *(utf++) = (0x80 | ((ucs &gt;&gt; 6) &amp; 0x6f))
</pre>
<p>which shows how complicated an expression looks when parentheses
are added indiscriminately.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e107" id="d0e107"></a>Coding
Standards and Guidelines</h2>
</div>
<p>In general - at least, in my experience - coding standards do
not provide rules on how to parenthesise expressions. I suspect
this is for two reasons. Firstly, because although all programmers
use parentheses to clarify the meaning of expressions, they may
well disagree on what makes an expression clear. Clarity seems a
matter of taste. While programmers in a team may agree (to differ)
on whether tabs or spaces are to be used for indentation, their
coding standard leaves them free to rewrite Example 4 as:</p>
<pre class="programlisting">
              str += errors == 0 ? &quot;succeeded&quot; : &quot;failed&quot;
</pre>
<p>And secondly, if a coding standard were to rule on how to
parenthesise, it would be difficult to find a middle ground. This
leaves as candidate rules the two extremes:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>parenthesise everything</p>
</li>
<li>
<p>never parenthesise</p>
</li>
</ul>
</div>
<p>The first quickly leads to unreadable code, and the second seems
overly proscriptive. In the absence of a hard rule, here are some
guidelines, which I hope are non-contentious, and which may help us
reach a conclusion:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>have the operator precedence tables to hand and understand how
to interpret expressions using them,</p>
</li>
<li>
<p>understand the logic behind the operator precedence tables, but
be aware of the traps and pitfalls,</p>
</li>
<li>
<p>remember, parentheses are not the only way to make order of
evaluation clear. For example, Ex 4 could be rewritten:</p>
<pre class="programlisting">
  *utf++ = 0x80 |
                ucs &gt;&gt; 6 &amp;
                0x6f
</pre>
<p>or even:</p>
<pre class="programlisting">
  *utf = ucs &gt;&gt; 6;
  *utf &amp;= 0x6f;
  *utf |= 0x80;
  ++utf;
</pre></li>
<li>
<p>if an expression is hard to understand, break it down into
simpler steps, or extract it out as a function with a meaningful
name,</p>
</li>
<li>
<p>trust the compiler: it might not implement partial template
specialisation correctly, but it will get operator precedence right
every time,</p>
</li>
<li>
<p>never use parentheses simply because you aren't sure how an
expression will be evaluated without them: treat doubt as an
opportunity to learn,</p>
</li>
<li>
<p>all macro arguments must be parenthesised.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e153" id="d0e153"></a>Concluding
Thoughts</h2>
</div>
<p>Any effort put into becoming familiar with precedence tables is
likely to pay off across a range of languages. For example,
although C++ introduces several new operators over C, there are no
surprises. The precedence rules remain in force even if the
operators have been overloaded (but that's the subject of another
article). Java operator precedence is almost a subset of C's.
Similarly, scripting languages are generally compatible with C,
even where C's precedence rules are slightly screwy<sup>[<a name=
"d0e158" href="#ftn.d0e158" id="d0e158">2</a>]</sup>. So, while
PERL introduces lower precedence versions of the logical operators
<tt class="function">not</tt>, <tt class="function">and</tt>, and
<tt class="function">or</tt>, it ensures that <tt class=
"function">not</tt> binds more tightly than <tt class=
"function">and</tt> which in turn binds more tightly than
<tt class="function">or</tt><sup>[<a name="d0e182" href=
"#ftn.d0e182" id="d0e182">3</a>]</sup>. Interestingly, in Python,
where whitespace is syntactically significant, parentheses can be
used not just to indicate order of evaluation, but also to wrap
lengthy expressions over several lines.</p>
<p>The more experienced I become as programmer, the fewer
parentheses I use. Coming from a mathematical background, it was
several months into my first job before I dared use the conditional
operator - and when I finally did start using it, I parenthesised
all the sub-expressions for safety. Later on in my career, when I
first found myself working with the bitwise operators, again, I
enclosed sub-expressions with brackets. As my confidence has
increased, the brackets have peeled away.</p>
<p>This, though, is simply evolution. Familiarity with the
languages you use makes it easier to read expressions without the
unnecessary noise of parentheses. Evolving in this way, however,
leaves a programmer vulnerable when working on code written by a
more experienced teammate, unless the experienced programmer writes
to a lowest common denominator.</p>
<p>Surely it would be better for everyone to program to a highest
common denominator. The operator precedence tables are a
fundamental part of the language. The rules for using them are
simple. Although there are many precedence levels, the operators do
group logically. Update your Coding Standards. Prohibit unnecessary
parentheses. Brackets off!</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e192" id="d0e192"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Koenig" id="Koenig"></a>
<p class="bibliomixed">[Koenig] Andrew Koenig, 1989, <span class=
"citetitle"><i class="citetitle">C Traps and Pitfalls</i></span>,
Addison-Wesley, ISBN 0-201-17928-8 2</p>
</div>
</div>
<div class="footnotes"><br>
<hr class="c2" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e92" href="#d0e92" id=
"ftn.d0e92">1</a>]</sup> This example is lifted straight from
[<a href="#Koenig">Koenig</a>], from the section headed: &quot;Operators
do not always have the precedence you want&quot;.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e158" href="#d0e158" id=
"ftn.d0e158">2</a>]</sup> According to [<a href=
"#Koenig">Koenig</a>], some of C's peculiarities can be blamed on
its heritage: &quot;The precedence of the C logical operators comes
about for historical reasons. B, the predecessor of C, had logical
operators that corresponded rougly to C's &amp; and | operators.
Although they were defined to act on bits, the compiler would treat
them as &amp;&amp;and || if they were in a conditional context.
When the two usages were split apart in C, it was deemed too
dangerous to change the precedence much.&quot;</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e182" href="#d0e182" id=
"ftn.d0e182">3</a>]</sup> This contrasts C/C++, where not, and and
or, if available, are equivalent to !, &amp;&amp; and ||
respectively.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
