    <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  :: Student Code Critique Competition 34</title>
        <link>https://members.accu.org/index.php/articles/817</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>




<div class="xar-mod-head"><span class="xar-mod-title">Student Code Critiques from CVu journal. + CVu Journal Vol 17, #3 - Jun 2005</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/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c184/">Journal Columns</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c183/">Code Critique</a>
<br />

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

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c96/">173</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c183-96/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c183+96/">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;Student Code Critique Competition 34</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 05 June 2005 05:00:00 +01:00 or Sun, 05 June 2005 05:00:00 +01: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><span class="bold"><b>Prizes provided by Blackwells Bookshops
&amp; Addison-Wesley</b></span></p>
<p class="c3"><span class="remark">Please note that participation
in this competition is open to all members. The title reflects the
fact that the code used is normally provided by a student as part
of their course work.</span></p>
<p class="c3"><span class="remark">This item is part of the
Dialogue section of C Vu, which is intended to designate it as an
item where reader interaction is particularly important. Readers'
comments and criticisms of published entries are always welcome, as
are possible samples.</span></p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e31" id="d0e31"></a>Before We
Start</h2>
</div>
<p>Remember that you can get the current problem set in the ACCU
website (<a href="http://www.accu.org/journals/" target=
"_top">http://www.accu.org/journals/</a>). This is aimed to people
living overseas who get the magazine much later than members in the
UK and Europe.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e39" id="d0e39"></a>Student Code
Critique 33 Entries</h2>
</div>
<p>Special thanks to <span class="bold"><b>Richard
Corden</b></span> for providing us with a snippet he came
across.</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>I'm having a problem whose cause I'm not able to detect. I
sometimes end up in the true block of the if statmement where
iter-&gt;first is not '5'. Could you explain me what is going
wrong?</p>
<pre class="programlisting">
#include &lt;map&gt;
#include &lt;algorithm&gt;
typedef std :: multimap &lt;int, int&gt; MyMapType;
//
// Filter on values between 5 and 10
struct InRange
{
  bool operator ()(MyMapType::value_type const
       &amp; value) const
  {
    return (value.second &gt; 5) &amp;&amp; (
        value.second &lt; 10);
  }
};

//
// Not really important how this happens.
void initMap (MyMapType &amp; map);

int main ()
{
  MyMapType myMap;

  // initialise the map...
  initMap (myMap);
  MyMapType::iterator lower = 
      myMap.lower_bound ( 5 );
  MyMapType::iterator iter = std :: find_if (
      lower, myMap.upper_bound ( 5 ),
      InRange () );

  //
  // Did we find this special criterial?
  if (iter != myMap.end ())
  {
    // 
    // Yup...we have a value meeting our 
       criteria
  }
  else
  {
  }
}
</pre></blockquote>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e52" id="d0e52"></a>From Seyed H.
Haeri <tt class="email">&lt;<a href=
"mailto:shhaeri@math.sharif.edu">shhaeri@math.sharif.edu</a>&gt;</tt></h3>
</div>
<p>First of all, I think I've got to 'fess up that this is the
first time - out of three (!) - that I feel satisfied after solving
the problem. In the previous times, the problem was more or less
trivial, and all we'd got to do was to suggest the programmer how
to improve his/her code. This time, we've got a real problem;
something which is likely to happen in real programming, and,
unfortunately, is not that much uncommon in the commercial world.
OK, and now the code, line-by-line:</p>
<p>The first two lines, i.e.</p>
<pre class="programlisting">
#include &lt;map&gt;
#include &lt;algorithm&gt;
</pre>
<p>Seem OK. Next we come across</p>
<pre class="programlisting">
typedef std::multimap&lt;int, int&gt; MyMapType;
</pre>
<p>(I'm wondering whether the lack of appropriate vertical spacing
here is due to lack of enough space in the journal, or is that
adjusted so by the programmer. If the latter is the case, add this
to the list of drawback of the code.)</p>
<p>This line by itself is OK as well. The programmer has correctly
observed the necessity of using <tt class="literal">typedef</tt>'s,
yet he/she has missed making the job complete. That is, he/she is
better to add the following as well:</p>
<pre class="programlisting">
typedef MyMapType::const_iterator 
        const_iterator;
</pre>
<p>The following two points about the above line worth
mentioning:</p>
<p>First, I've chosen to use <tt class=
"classname">MyMapType::const_iterator</tt> over <tt class=
"classname">MyMapType::iterator</tt> as <tt class=
"literal">const</tt>-correctness implies that according to our
usage. This will become clearer as we proceed. (Note that Item#26
of Effective STL does not apply here.)</p>
<p>Second, I've chosen <tt class="literal">typedef</tt>ed
<tt class="classname">MyMapType::const_iterator</tt> as <tt class=
"literal">const_iterator</tt> rather than <tt class=
"literal">iterator</tt> to clarify it for the (potential) code
reader that I'm using constant iterators.</p>
<p>I'd like to add the following <tt class="literal">typedef</tt>s
according to similar reasons:</p>
<pre class="programlisting">
typedef MyMapType::value_type value_type;
typedef MyMapType::key_type key_type;
</pre>
<p>Next:</p>
<pre class="programlisting">
struct InRange
{
  bool operator () (const MyMapType::
      value_type&amp; value) const
  {
    return (value.second &gt; 5) &amp;&amp; 
           (value.second &lt; 10);
  }
};
</pre>
<p>Although there is no &quot;problem&quot; on retaining this predicate as a
function object, it is better to be transformed to its pure
function counterpart. (Consult Item#39 for more on the reason.)</p>
<p>Furthermore, those two magic numbers 5 and 10 are asking us to
turn them into constants. (See Item#2 of C++ Gotchas for more on
magic numbers.) As they apply only to the predicate itself, I'd
prefer to make them template parameters. Therefore, here my refined
version:</p>
<pre class="programlisting">
template &lt;int lBound, int uBound&gt;
bool inRange(const value_type&amp; value)
{
  return (value &gt; lBound) &amp;&amp; (value &lt; uBound);
}
</pre>
<p>The comment of</p>
<pre class="programlisting">
void initMap(MyMapType&amp; map);
</pre>
<p>Urges me leaving it off, and I'll obey that! Afterwards, there
is no special point about the following lines.</p>
<pre class="programlisting">
int main()
{
  MyMapType myMap;

  initMap(myMap);
</pre>
<p>until we reach</p>
<pre class="programlisting">
  MyMapType::iterator lower = 
        myMap.lower_bound(5);
</pre>
<p>Here is the first place where we should use <tt class=
"literal">const_iterator</tt> instead of <tt class=
"classname">MyMapType::iterator</tt>. I say that because we've
nowhere tried to manipulate the result of dereferencing of
lower.</p>
<p>Furthermore, supposing that this code is going to have enough
functionality, 5 turns out to become another magic number. Thus,
this is how I refine the above line:</p>
<pre class="programlisting">
const key_type rangeVal = 5;
const_iterator lower = myMap.lower_bound(rangeVal);
</pre>
<p>The next line is where the programme goes logically wrong.
Hereafter, the programmer has wrongly assumed that he/she has found
&quot;an exact&quot; occurrence of 5 unless he's reached to the end of
<tt class="varname">myMap</tt>. And that's wrong. That's exactly
what has caused him to get astonished by the result of programme
execution. I guess the following snippet from the Standard should
make it easier to explain what's going on here (row 9 of Table
69):</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>&quot;a.lower_bound(k) &hellip; returns an iterator pointing to the
first element with key not less than k.&quot;</p>
</blockquote>
</div>
<p>That is, it does not guarantee that it will return an iterator
to an element with the exact key k. Consider the following
multi-map for example</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>{&lt;1, &hellip;&gt;, &lt;1, &hellip;&gt;, &lt;2, &hellip;&gt;,
&lt;3, &hellip;&gt;, &lt;6, &hellip;&gt;, &hellip;}</p>
</blockquote>
</div>
<p>Where lower would return &lt;6, &hellip;&gt; - in which the key
is not 5. Yet it is the first key not less than 5. Accordingly, I
change the next line to the following:</p>
<pre class="programlisting">
  if(lower-&gt;first == rangeVal)//if exact match
        found
  {
    const int lBound(5), uBound(10);

    const_iterator iter = 
      std::find(lower, 
                myMap.upper_bound(rangeVal), 
                inRange&lt;lBound, uBound&gt;);

    if(iter != myMap.end())
    {
      //&hellip;
    }
    else
    {}
  }
}
</pre>
<p>A supplementary point about the above programme is that as Scott
Meyers explains in Item#45 of Effective STL, if you need to know
where the range (potentially) containing what you need is located,
you should use std::equal_range(). Considering that, the programme
will become:</p>
<pre class="programlisting">
std::pair&lt;const_iterator, const_iterator&gt; p =
  myMap.equal_range(rangeVal);

//See Item#45 of Effective STL for why this
      works

if(p.first != p.second)//if there is an exact 
      match at all
{
  const_iterator iter = 
    std::find(p.first, p.second,
        inRange&lt;lBound, uBound&gt;);

  if (iter != p.second)//we've got a value
      meeting our criteria
  {
    //&hellip;
  }
  else
  {}
//&hellip;
</pre>
<p>This programmer seems to know enough of the basics of STL
programming. Yet, he/she lacks deep-enough knowledge of STL. I
suggest reading the following books by order:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><i class="citetitle">Generic Programming and the STL: Using and
Extending the C++ Standard Library</i> by Mathew H. Austern</p>
</li>
<li>
<p><i class="citetitle">Effective STL: 50 Specific Ways to Improve
Your Use of Standard Template Library</i> by Scott Meyers.</p>
</li>
</ul>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e178" id="d0e178"></a>From Nick Buller
<tt class="email">&lt;<a href=
"mailto:nickbuller@hotmailcom">nickbuller@hotmailcom</a>&gt;</tt></h3>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e183" id="d0e183"></a>Program
Structure</h4>
</div>
<p>As has been mentioned many times the program entry point
<tt class="literal">int main()</tt> is defined as returning an
<tt class="type">int</tt> value but no return statement is present
in the main code block. The general program structure should be as
follows:</p>
<pre class="programlisting">
int main()
{
  // Program code omitted for brevity
  return 0;
}
</pre>
<p>As mentioned in Francis' commentary for SCC28 &quot;... the default
form of the definition of main should encapsulate its code in a try
block&quot;.</p>
<p>I also add the correct include and the using block as I prefer
the code not to be littered with <tt class="literal">std::</tt>, so
the main function becomes:</p>
<pre class="programlisting">
#include &lt;iostream&gt;

using std::endl;
using std::cerr;

int main()
{
  try
  {
    // Program code omitted for brevity
  }
  catch(...)
  {
    cerr &lt;&lt; &quot;An unexpected exception&quot;
            &quot; occurred.&quot; &lt;&lt; endl;
    return 1;
  }

  return 0;
}
</pre></div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e205" id="d0e205"></a>Constants Not
Magic Numbers</h4>
</div>
<p>As with reams of code that I have tried to decode the code
contains magic numbers. I believe that the code I write will be
read more often by other people then by myself (lets take it as a
given they are looking for a bug). So we should try and make life
simple rather than expect they automagically understand the magic
number left provide them with a good starting point.</p>
<p>Rather than writing</p>
<pre class="programlisting">
return (value.second &gt; 5) &amp;&amp; (value.second &lt;
       10);
</pre>
<p>Write the following</p>
<pre class="programlisting">
static const int someMeaningFullName = 5;
static const int someOtherMeaningFullName 
    = 10;

...

return (value.second &gt; someMeaningFullName)
  &amp;&amp; (value.second&lt;someOtherMeaningFullName);
</pre></div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e218" id="d0e218"></a>Comment What Are
You Trying To Achieve</h4>
</div>
<p>Now that you have code that can be understood a comment would
not hurt.</p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e223" id="d0e223"></a>Variable
Names</h4>
</div>
<p>Forgive me but <tt class="classname">MyMapType</tt>, or should
it be <tt class="classname">OurMapType</tt>, Ummm. The name of the
<tt class="literal">mapType</tt> should indicate its use.
Unfortunately as no comments, well-defined constants or comments
exist no recommendations can be made.</p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e237" id="d0e237"></a>On a Personal
Note</h4>
</div>
<p>I dislike the following code for 3 reasons: -</p>
<pre class="programlisting">
MyMapType::iterator lower = 
      myMap.lower_bound(5);
MyMapType::iterator iter = std :: find_if
      (lower, myMap.upper_bound(5), 
      InRange());
</pre>
<div class="orderedlist">
<ol type="1">
<li>
<p>A local variable is used to store the lower bound iterator but
the second is called directly and passed to the function.</p>
</li>
<li>
<p><tt class="literal">myMap.upper_bound(5)</tt> returns an
iterator by value so there is no reason not to store it in a local
variable as is used for the lower_bound return or at least be
consistent.</p>
</li>
<li>
<p>The call to <tt class="function">std::find_if</tt> is split on 2
lines and the second line is not indented.</p>
</li>
</ol>
</div>
<p>Code like this can be a nightmare to read.</p>
<pre class="programlisting">
MyMapType::iterator lower = 
      myMap.lower_bound(5);
MyMapType::iterator upper = 
      myMap.upper_bound(5);

MyMapType::iterator iter = std :: find_if(
      lower, upper, InRange());
</pre></div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e263" id="d0e263"></a>A Solution</h4>
</div>
<p>A single line change to the code would provide a fix to the
problem: -</p>
<pre class="programlisting">
if (iter != myMap.end())
</pre>
<p>would be replaced by</p>
<pre class="programlisting">
if (iter != upper)
// or if (iter != myMap.upper_bound(5))
</pre></div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e274" id="d0e274"></a>The Problem</h4>
</div>
<p>To understand what is happening we need to look at the
definition of the multimap and its members:</p>
<pre class="programlisting">
template &lt;class Key, class T, class Compare = 
   less&lt;Key&gt;, class Allocator = allocator&lt;T&gt; &gt;
</pre>
<p>The definition of <tt class="varname">myMap</tt> is only
parameterised on <tt class="literal">&lt;int, int&gt;</tt> so the
default <tt class="classname">Compare</tt> and <tt class=
"classname">Allocator</tt> will be used, in this case we are
interest in <tt class="function">less&lt;Key&gt;</tt>. If
<tt class="literal">f</tt> is an object of <tt class=
"literal">class less&lt;T&gt;</tt> and <tt class="literal">x</tt>
and <tt class="literal">y</tt> are objects of <tt class=
"literal">class T</tt>, then <tt class="literal">f(x,y)</tt>
returns true if <tt class="literal">x &lt; y</tt> and false
otherwise.</p>
<pre class="programlisting">
const_iterator lower_bound(const key_type&amp; x) 
      const;
const_iterator upper_bound(const key_type&amp; x) 
      const;
</pre>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><tt class="literal">myMap.lower_bound(5)</tt> will find the
first <tt class="literal">myMap</tt> element whose key is not less
than 5, if no value is found then <tt class=
"literal">myMap.end()</tt> is returned.</p>
</li>
<li>
<p><tt class="literal">myMap.upper_bound(5)</tt> will find the
first <tt class="literal">myMap</tt> element whose key is greater
than or equal to 5, if no value is found then <tt class=
"literal">myMap.end()</tt> is returned.</p>
</li>
</ul>
</div>
<p>If the map contains the values (5, x), <tt class=
"literal">lower_bound</tt> will return an iterator to the one and
only entry and upper bound.</p>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e349" id="d0e349"></a>Commentary</h3>
</div>
<p>I suspect that many readers were scared off by this SCC, which
reflects people's lack of familiarity with <tt class=
"classname">std::multimap</tt>. If you are one such reader then I
encourage you to explore the range of associative containers in the
standard library - in my experience most people always use
<tt class="classname">std::map</tt> even where another container
might be better. The fundamental problem with the code shown is the
test</p>
<pre class="programlisting">
if (iter != myMap.end ())
</pre>
<p>to detect failure to find an element in the map. What is wrong
with this test? The value of <tt class="literal">iter</tt> on
failure is the end of the range not the end of the container. The
range ends with <tt class="literal">upper_bound(5)</tt>, so this is
the value against which <tt class="literal">iter</tt> must be
tested to see if a match was found.</p>
<p>In this example the use of <tt class="classname">multimap</tt>
was really a bit of a red herring and simply having a good
understanding of the use of standard library iterators would have
been enough to spot the bug.</p>
<p>A subsidiary problem is the lack of detail in report of the
problem. When a failure occurs it would be more helpful to know
what the value of the key is (and ideally the complete contents of
the container). This could be a good place to start talking with
the student about error handling, fault reporting, and designing
for testability.</p>
<p>The first solution presented above does fix the bug and moreover
covers some other problems with the code. There is even a quotation
of the relevant section from the standard to explain what is going
wrong. Unfortunately the standard is designed for precision and the
technical vocabulary used is not always clear to casual
readers!</p>
<p>I do however have a (minor) criticism with the above solution in
that I think the first book listed may be too advanced for a
student at this stage. I would suggest getting started with the
collection classes via a good basic tutorial to using the STL, such
as &quot;The C++ Standard Library&quot; by Nicolai Josuttis and progressing
to Austern's book later on.</p>
<p>The second solution presented makes it easy for the student - a
one line solution to the bug is given. The first remark - that main
requires a &quot;return 0&quot; - is one of those things that is true in
practice but not in theory&hellip; The standard states that main is
a special function and that a return statement is not required. One
popular compiler does not support that exclusion - so for maximum
portability it is probably a good idea to add an explicit return
statement.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e386" id="d0e386"></a>The Winner of
SCC 33</h3>
</div>
<p>The editor's choice is: <span class="bold"><b>Sayed H.
Haeri</b></span></p>
<p>Please email <tt class="email">&lt;<a href=
"mailto:francis@robinton.demon.co.uk">francis@robinton.demon.co.uk</a>&gt;</tt>
to arrange for your prize.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e398" id="d0e398"></a>Student Code
Critique 34</h2>
</div>
<p><span class="bold"><b>(Submissions to scc@accu.org by July
10th)</b></span></p>
<p>Here is a problem with a 'C' program. Please try to both solve
the student's current problem and also help them learn from this
mistake.</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>I send an unsigned char called tipus which is meant to be some
hex number from 0x00 to 0xff and which should decide the string to
be returned...</p>
<p>If the unsigned int called valor I send is above 0xA000 I use
the struct &quot;decidetest&quot; to send a string back, else, I send a
string selected from the struct &quot;decide&quot;.</p>
<p>If no substitution is made, then the string returned is always a
space in html...&quot;&amp;nbsp; &quot;</p>
<p>For some reason I always get the &quot;static char escape&quot; string
returned... any idea? (the function compiles all right...)</p>
<pre class="programlisting">
char* Detect_type(unsigned char tipus, 
      unsigned int valor)
{
int i;
static char escape[16] = &quot;&amp;nbsp;        &quot;;
static struct decide {
unsigned num;
char *string;
} cadena [] = {
         {0x00, &quot;Sobre V PK      &quot;},
         {0x02, &quot;Sobre V RMS     &quot;},
         {0x0E, &quot;--Power OFF--&quot;},
         {0x10, &quot;--Power ON--&quot;},
         {0xff, &quot;                &quot;},
};

static struct decidetest {
unsigned numero;
unsigned char num;
char *string;
} cadenatest [] = {
         {0x00, &quot;Sobre V PK  Test&quot;},
         {0x02, &quot;Sobre V RMS Test&quot;},
         {0x0E, &quot;--Power OFF--&quot;},
         {0x10, &quot;--Power ON--&quot;},
         {0xff, &quot;                &quot;},
};

if (valor &gt;= 0xA000)
  {
    for(i = 0; i &lt; sizeof(cadenatest) /
        sizeof(cadenatest[0]); i++)
    if(cadenatest[i].num == tipus)
      return cadenatest[i].string;
  }
else
  {
    for(i = 0; i &lt; sizeof(cadena) /
        sizeof(cadena[0]); i++)
    if(cadena[i].num == tipus)
      return cadena[i].string;
  }

return (escape);
}
</pre></blockquote>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
