    <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 33</title>
        <link>https://members.accu.org/index.php/articles/802</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, #2 - Apr 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/c97/">172</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c183+97/">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 33</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 06 April 2005 13:16:11 +01:00 or Wed, 06 April 2005 13:16:11 +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="c2"><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="c2"><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.</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 at people
living overseas who get the magazine much later than members in
Europe.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e39" id="d0e39"></a>Student Code
Critique 32 Entries</h2>
</div>
<p>I still wonder about the lack of knowledge (or rather awareness)
among beginners of the extensive functionality offered by the
standard library. Let this be reflected in your answer to the
student, with a corresponding solution.</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>This computes the product of two N by N matrices. It works fine
in cygwin compiler, but it doesn't in VC++. The strange thing is
when I have N = 2 no problem, but N = 3 makes problem. I am not
sure I use 'new' operator correctly in the following program. Can
someone help in finding the problem here ?</p>
<pre class="programlisting">
#include &lt;iostream.h&gt;
#include &lt;process.h&gt;
void main(void) {
  int N, i, j, k;
  double **A, **B, **C;
  double sum = 0.0;
  cout &lt;&lt; &quot;Dimension of Matrix ?&quot; &lt;&lt; endl;
  cin &gt;&gt; N;
  A = new (double *);
  B = new (double *);
  C = new (double *);
  for(i=0; i&lt;N; i++){
    A[i] = new double[N];
    B[i] = new double[N];
    C[i] = new double[N];
  }
  for(i=0; i&lt;N; i++)
    for(j=0; j&lt;N; j++){
      cout &lt;&lt; &quot;A[&quot; &lt;&lt; i &lt;&lt; &quot;][&quot; &lt;&lt; j &lt;&lt; &quot;] = ?&quot; &lt;&lt; endl;
      cin &gt;&gt; A[i][j];
    }
  for(i=0; i&lt;N; i++)
    for(j=0; j&lt;N; j++){
      cout &lt;&lt; &quot;B[&quot; &lt;&lt; i &lt;&lt; &quot;][&quot; &lt;&lt; j &lt;&lt; &quot;] = ?&quot; &lt;&lt; endl;
      cin &gt;&gt; B[i][j];
    }
  for(k=0; k&lt;N; k++)
    for(i=0; i&lt;N; i++){
      sum = 0.0;
      for(j=0; j&lt;N; j++)
        sum += A[i][j]*B[j][k];
      C[i][k] = sum;
    }
  cout &lt;&lt; endl &lt;&lt; endl &lt;&lt; endl;
  for(i=0; i&lt;N; i++)
    for(j=0; j&lt;N; j++)
      cout &lt;&lt; &quot;C[&quot; &lt;&lt; i &lt;&lt; &quot;][&quot; &lt;&lt; j &lt;&lt; &quot;] = &quot;
           &lt;&lt; C[i][j] &lt;&lt; endl;
}
</pre></blockquote>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e49" id="d0e49"></a>From &quot;The Cart
Horse&quot;</h3>
</div>
<p>This is an interesting case; the student knows they have a
problem and have even gone to the extent of trying the program on
two different compilers. However they don't seem to know what to do
with the results of their test! The first thing to do was to try
and reproduce the problem.</p>
<p>This was surprisingly hard - I compiled the code and tested it
with a matrix size of 3 and it seemed to work perfectly with
Microsoft VC 6.0.</p>
<p>Microsoft VC 7.1 failed to compile the program - <tt class=
"filename">&lt;iostream.h&gt;</tt> is obsolete - so I changed it to
the ISO standard <tt class="filename">&lt;iostream&gt;</tt> and
added the appropriate <tt class="literal">std::</tt> prefixes to
<tt class="classname">cin</tt>, <tt class="classname">cerr</tt> and
<tt class="classname">endl</tt>. The code again seemed to work
faultlessly.</p>
<p>I next tried mingw and gcc also complained that the program used
<tt class="filename">iostream.h</tt> not <tt class=
"filename">iostream</tt> (so I used the file fixed for VC 7.1) and
it also complained that main should return <tt class=
"type">int</tt>. So I'm not sure what version of gcc the student
was using.</p>
<p>My first response in this sort of situation would usually be to
try and get a better fault report from the student. I'd want the
answer to three questions:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>What version of the compiler(s) are you using?</p>
</li>
<li>
<p>What command line are you using?</p>
</li>
<li>
<p>What are the actual symptoms of the problem?</p>
</li>
</ol>
</div>
<p>However the Student Code Critique is not interactive in this
sense so I'll just press on...</p>
<p>What does it mean when a program works when compiled with one
compiler but not with another?</p>
<p>In my experience this is usually because the program accesses
memory it shouldn't be using. The underlying problem probably
occurs with the code generated by both compilers, but there are no
(obvious) symptoms with one of them. This is because the actual
layout of memory is different in the two compilers (or even with
the same compiler when, for example, the optimiser is turned
on).</p>
<p>It is very often worth compiling and running a program with
multiple compilers - sometimes you get more information from
additional compiler warnings and other times the runtime error
handling provides additional clues to the problem.</p>
<p>In this case we only have the program failing with one compiler,
and even worse I can't reproduce it. So without more ado let's dive
into the code itself.</p>
<p>On reading the code it is fairly clear what the problem is; the
first allocation of memory for the variables <tt class=
"varname">A</tt>, <tt class="varname">B</tt> and <tt class=
"varname">C</tt> does not involve <tt class="varname">N</tt>.</p>
<p><tt class="literal">new (double *)</tt> allocates enough memory
for a single <tt class="type">double*</tt> - but we actually want
an array of <tt class="varname">N</tt> pointers.</p>
<p>It is at first sight surprising that the code works at all - it
just goes to show that writing only a little bit off the end of
allocated memory can sometimes seem to work!</p>
<p>So it would be very easy to suggest the student changes:</p>
<pre class="programlisting">
A = new (double *);
</pre>
<p>to:</p>
<pre class="programlisting">
A = new double*[N];
</pre>
<p>and similarly for <tt class="varname">B</tt> and <tt class=
"varname">C</tt>.</p>
<p>But is this helpful? As the saying has it, &quot;give a man a fish
and you feed him for a day, teach a man to fish and you feed him
for life&quot;.</p>
<p>There are some other problems also lurking in this code but
attempting to fix them directly leads into deeper waters.</p>
<p>I would recommend that most users of C++ start out by staying
well away from <tt class="literal">operator new</tt> and letting
the standard library allocate the memory for them where
possible.</p>
<p>So, looking at the problem with a library user's hat on, what do
I want?</p>
<p>I want a class which gives me the characteristics of a
matrix.</p>
<p>Sadly the standard library doesn't come with one of these - but
it does supply a <tt class="classname">vector</tt> class and we can
create a matrix by having a <tt class="classname">vector</tt> of
<tt class="classname">vector</tt>s. Alternatively we can search for
a <tt class="classname">matrix</tt> class that we can download from
the Internet. A quick search with &quot;C++ matrix class&quot; reveals
several possible candidates.</p>
<p>If we want to stick with the standard library solution then we
can define a <tt class="classname">row</tt> as a <tt class=
"classname">vector</tt> of <tt class="type">double</tt> and a
<tt class="classname">matrix</tt> as a <tt class=
"classname">vector</tt> of <tt class="classname">row</tt>s:</p>
<pre class="programlisting">
#include &lt;vector&gt;
class row : public std::vector&lt;double&gt; {};
class matrix : public std::vector&lt;row&gt; {};
</pre>
<p>Now the code to initialise the matrices is a matter of resizing
the vectors rather than allocating the memory ourselves. This has
several benefits over using raw pointers</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>it is easier to code correctly</p>
</li>
<li>
<p>the vectors will ensure the memory is freed when the function
return</p>
</li>
<li>
<p>if we are still having memory problems, we could use a debugging
version of the standard library to trap out of range indices.</p>
</li>
</ul>
</div>
<p>I hate writing anything twice, so I would probably suggest the
student writes a simple helper function and calls it when needing
to initialise a matrix:</p>
<pre class="programlisting">
void init(matrix &amp; A, int size) {
  A.resize(size);
  for(int idx = 0; idx != size; ++idx)
    A[idx].resize(size);
}
</pre>
<p>This would make the code as presented work immediately and the
student would also hopefully have less problems with memory
allocation in future.</p>
<p>I might suggest, as an exercise for the student, that they move
the matrix multiplication into a separate function so it could be
reused and to improve the readability of the code. I would probably
initially suggest a free standing function with a prototype like
this:</p>
<pre class="programlisting">
matrix operator*(matrix const &amp; A, matrix const &amp; B);
</pre>
<p>So my initial solution to the student's problem looks like
this:</p>
<pre class="programlisting">
#include &lt;iostream&gt;
#include &lt;vector&gt;
class row : public std::vector&lt;double&gt; {};
class matrix : public std::vector&lt;row&gt; {};
void init(matrix &amp; A, int size) {
  A.resize(size);
  for(int idx = 0; idx != size; ++idx)
    A[ idx ].resize( size );
}
matrix operator*(matrix const &amp; A, matrix const &amp; B) {
  int const N(A.size());
  matrix result;
  init(result, N);
  for(int k=0; k&lt;N; k++)
    for(int i=0; i&lt;N; i++) {
      double sum = 0.0;
      for(int j=0; j&lt;N; j++)
        sum += A[i][j]*B[j][k];
      result[i][k] = sum;
    }
  return result;
}
int main(void) {
  int N, i, j;
  matrix A, B;
  std::cout &lt;&lt; &quot;Dimension of Matrix ?&quot; &lt;&lt; std::endl;
  std::cin &gt;&gt; N;
  init(A, N);
  init(B, N);
  for(i=0; i&lt;N; i++)
    for(j=0; j&lt;N; j++) {
      std::cout &lt;&lt; &quot;A[&quot; &lt;&lt; i &lt;&lt; &quot;][&quot; &lt;&lt; j &lt;&lt; &quot;] = ?&quot;
                &lt;&lt; std::endl;
      std::cin &gt;&gt; A[i][j];
    }
  for(i=0; i&lt;N; i++)
    for(j=0; j&lt;N; j++) {
      std::cout &lt;&lt; &quot;B[&quot; &lt;&lt; i &lt;&lt; &quot;][&quot; &lt;&lt; j &lt;&lt; &quot;] = ?&quot;
                &lt;&lt; std::endl;
      std::cin &gt;&gt; B[i][j];
    }
  matrix C = A * B;
  std::cout &lt;&lt; std::endl &lt;&lt; std::endl &lt;&lt; std::endl;
  for(i=0; i&lt;N; i++)
    for(j=0; j&lt;N; j++)
      std::cout &lt;&lt; &quot;C[&quot; &lt;&lt; i &lt;&lt; &quot;][&quot; &lt;&lt; j &lt;&lt; &quot;] = &quot;
                &lt;&lt; C[i][j] &lt;&lt; std::endl;
  return 0; // keeps MSVC happy
}
</pre>
<p>We would then have two free-standing functions operating on
objects of the <tt class="classname">matrix</tt> class; we can then
move on to suggest ways in which the <tt class="classname">row</tt>
and <tt class="classname">matrix</tt> classes could be enhanced by
using member functions and constructors. We might then move on to
discuss using composition rather than inheritance.</p>
<p>There are a number of other ways this solution could also be
improved, for example to generalise by data type or to improve the
input and output, but at this stage I suspect trying to do any more
would simply confuse things for the student.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e239" id="d0e239"></a>From Calum Grant
<tt class="email">&lt;<a href=
"mailto:calum@visula.org">calum@visula.org</a>&gt;</tt></h3>
</div>
<p>The main problem with this code is that it is structured badly.
You should always split long functions up into small simple units,
which makes programs clearer and more reusable. It also makes it
easier to test. Whenever you write code, turn it into generic
functions or classes that can be reused. So what you really want is
a general-purpose <tt class="classname">Matrix</tt> class that you
can use in any application that requires a matrix. Rewrite your
<tt class="function">main()</tt> function to look something like
this:</p>
<pre class="programlisting">
int main() { 
  Matrix a, b; 
  int size = input_matrix_size(); 
  input_matrix(size, a); 
  input_matrix(size, b); 
  std::cout &lt;&lt; a * b; 
  return 0; 
}
</pre>
<p>This makes the <tt class="function">main()</tt> function much
clearer, and all the real work is done elsewhere. We have changed
the return type of <tt class="function">main()</tt> function to be
standards conforming, and it is conventional to <tt class=
"literal">return 0</tt> from <tt class="function">main()</tt> to
indicate no error. Other minor problems with your code are that it
is in general preferable to use pre-increment <tt class=
"literal">++j</tt> instead of postincrement <tt class=
"literal">j++</tt> and that you should <tt class="literal">#include
&lt;iostream&gt;</tt>, not the deprecated <tt class=
"literal">&lt;iostream.h&gt;</tt>. That will require you to put
<tt class="literal">using namespace std</tt> in your code, or else
qualify <tt class="classname">cout</tt>, <tt class=
"classname">cin</tt> and <tt class="classname">endl</tt> with
<tt class="literal">std::</tt>. Don't <tt class="literal">#include
&lt;process.h&gt;</tt>, that isn't needed. Your code should check
that its inputs are valid.</p>
<p>The constructor of the <tt class="classname">Matrix</tt> class
should allocate the data, while the destructor should free the
data. This highlights another problem with your code: you don't
free the arrays. In commercial software, forgetting to free memory
can be disastrous since the system will eventually run out of
memory. Therefore we need to pass the size of the array to the
constructor, and since we are writing a library class, we might as
well cater for non-square matrices as well. Your code did not work
reliably because you did not allocate the first array correctly, it
should be an array of size N of arrays of size N. Note also how the
array is deleted in the destructor, it is important to use the
<tt class="literal">delete []</tt> notation when deleting an array,
since this will matter when objects in the array have
destructors.</p>
<p>One should hide the internal data of the class by making it
private, and access and manipulate the data via accessor methods.
One can overload the <tt class="literal">[]</tt> operator to access
the cells of the matrix, so that if you have a matrix <tt class=
"varname">m</tt>, you can write <tt class="literal">m[x]</tt> to
access a column in your matrix, and therefore <tt class=
"literal">m[x][y]</tt> to access a particular cell. So here is a
<tt class="classname">Matrix</tt> class that allocates the data,
and provides accessor methods:</p>
<pre class="programlisting">
class Matrix1 {
  unsigned width, height; 
  double **cols; 
public: 
  Matrix1(unsigned w, unsigned h)
      : width(w), height(h) {
    cols = new double*[height]; 
    for(unsigned i=0; i&lt;width; ++i) 
      cols[i] = new double[height]; 
  }
  ~Matrix1() {
    for(unsigned i=0; i&lt;width; ++i) 
      delete [] cols[i]; 
    delete [] cols; 
  }
  double *operator[](unsigned col) {return cols[col];} 
  unsigned get_width()  { return width; } 
  unsigned get_height() { return height; } 
};
</pre>
<p>So we're done right? Not by a long way! The most important
problem is safety, and at the moment the copy constructor and the
assignment operator don't work correctly, so writing</p>
<pre class="programlisting">
a = b; 
Matrix x = y;
</pre>
<p>will crash the program. The compiler provides default
implementations that will in this case do the wrong thing. It will
only copy the pointer, so some arrays will not be freed, whilst
other arrays will be freed twice. The constructor of <tt class=
"classname">Matrix</tt> is not exception safe, and could leak
memory on an exception. Making the class robust and writing safe
copy constructors and assignment operators would be
straightforward, but quite laborious. The code does not initialize
the cells in the matrix to zero, which would be a nice feature of
the constructor.</p>
<p>You can replace C-style arrays with <tt class=
"classname">std::vector</tt>, and your code becomes</p>
<pre class="programlisting">
class Matrix2 {
  unsigned width, height; 
  std::vector&lt;std::vector&lt;double&gt; &gt; cols; 
public: 
  Matrix2(int w, int h) : width(w), height(h),

      cols(w, std::vector&lt;double&gt;(h)) {}
  std::vector&lt;double&gt; &amp;operator[](unsigned col)
                        { return cols[col]; } 
  unsigned get_width()  { return width; } 
  unsigned get_height() { return height; } 
}; 
</pre>
<p>This code is much shorter, clearer, nicer and safer, since all
of the functionality we need has already been implemented by the
<tt class="classname">vector</tt> class, and all of the default
methods like copy construction, assignment and destruction are all
taken care of by the <tt class="classname">vector</tt>. The
<tt class="literal">:</tt> notation in the <tt class=
"classname">Matrix</tt> is used to initialize its members, which
initializes the array with <tt class="varname">w</tt> elements each
a vector of length <tt class="varname">h</tt>, and the <tt class=
"classname">vector</tt> initializes the contents to zero.</p>
<p>The moral of the story is that one should almost never use
pointers and arrays, always use STL containers and iterators.
Because Matrix is a generic container, it should comply with the
norms of the STL as much as possible. This allows it to be used
with STL-compliant algorithms, and will make it easier to use and
understand. So it needs as much standard functionality as
appropriate, such as a <tt class="methodname">begin()</tt>,
<tt class="methodname">end()</tt>, <tt class=
"classname">iterator</tt>, <tt class=
"classname">const_iterator</tt>, <tt class=
"classname">reverse_iterator</tt>, <tt class=
"methodname">swap()</tt>, <tt class="methodname">at()</tt> and
operators like <tt class="methodname">+</tt>, <tt class=
"methodname">-</tt>, <tt class="methodname">*</tt>. One should
provide <tt class="literal">const</tt> and non-<tt class=
"literal">const</tt> versions of methods, so that the container is
usable when <tt class="literal">const</tt>. Implement operators
<tt class="methodname">&lt;&lt;</tt> and <tt class=
"methodname">&gt;&gt;</tt> to read and write the matrix to a
stream. Like other containers, it should be templated on the type
it contains, so that we could could have a matrix of any type of
value, such as <tt class="type">integer</tt>s, <tt class=
"type">bool</tt>s, <tt class="type">float</tt>s, <tt class=
"type">std::complex</tt> or even other matrices. One might also
perform bounds checking.</p>
<p>Although <tt class="classname">std::vector</tt> provides a
perfectly acceptable solution, the C++ STL has <tt class=
"classname">std::valarray</tt>, that is intended specifically for
writing multi-dimensional arrays. It is much more versatile since
it can use &quot;slices&quot;, linear subsets of an array, based upon
FORTRAN's BLAS (Basic Linear Algebra Subprograms) library, offering
high-performance multi-dimensional array manipulation. [<a href=
"#">Stroustroup</a>] provides an implementation of a <tt class=
"classname">Matrix</tt> class based upon valarray and slices, so I
do not need to repeat it here. A slice can represent any linear
subsequence of an array, so can represent both a row and a column.
However it may be easier to organize the array into columns and
just return the correct offset into the array.</p>
<pre class="programlisting">
T *operator[](unsigned col)
                       { return &amp;data[height*col]; } 
const T *operator[](unsigned col) const
                       { return &amp;data[height*col]; } 
</pre>
<p>If the size of the matrix is fixed, it may be better to specify
the dimensions of the matrix in template parameters. This has the
advantage that the compiler can then generate optimal code by
unrolling loops, and the contents of the matrix can be stored
inside the matrix object itself, rather than performing additional
memory allocation and deallocation.The crucial benefit is that the
dimensions of the matrices can be checked by the compiler, so that
matrices of the wrong sizes are prevented from being added or
multiplied, and the compiler can check that a matrix is square for
certain operations. It is much better to catch errors at
compile-time than run-time.</p>
<pre class="programlisting">
template&lt;typename T, unsigned W, unsigned H=W&gt; 
class Matrix3 {
  T cells[W][H]; 
public: 
  T *operator[](unsigned col) { return cells[col]; } 
  const T *operator[](unsigned col) const
                              { return cells[col]; } 
  unsigned get_width() const  { return W; } 
  unsigned get_height() const { return H; } 
}; 
template&lt;typename T, unsigned W,
         unsigned H, unsigned N&gt; 
Matrix3&lt;T,W,H&gt; operator*(const Matrix3&lt;T, N, H&gt; &amp;m1,
                       const Matrix3&lt;T, W, N&gt; &amp;m2) {
  Matrix3&lt;T,W,H&gt; result; 
  for(unsigned i=0; i&lt;W; ++i) {
    for(unsigned j=0; j&lt;H; ++j) {
      T sum = T(); // Initializes to zero
      for(unsigned k=0; k&lt;N; ++k) 
        sum += m1[k][i] * m2[j][k]; 
      result[i][j] = sum; 
    } 
  } 
  return result; 
}
</pre>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e443" id="d0e443"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Stroustrup" id="Stroustrup"></a>
<p class="bibliomixed">[Stroustrup] Bjarne Stroustrup, <span class=
"citetitle"><i class="citetitle">The C++ Programming Language, 3rd
Ed</i></span>, Addison Wesley 1997.</p>
</div>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e451" id="d0e451"></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>The first thing which jumps out at me as I skim through the code
is the lack of any (appropriate) commenting. The code has got no
comments at all, which means a big drawback to any code. The
student would lose a large amount of marks if he/she was a student
of mine. Not only each mentally separate piece of code needs its
own comment(s), but also the code needs to be commented - say at
the beginning of the program - for its (potential) reader about
what it's generally supposed to do. The next overall point about
this code is that the student has well tested the program, yet
he/she hasn't developed any diagnosis. He/she could have done that
say by observing the size of what he/she allocates (using the
<tt class="literal">sizeof</tt> operator, for example).</p>
<p>I then start wondering whether this code really flawlessly gets
compiled under any standard conforming implementation. The student
has used <tt class="classname">std::cout</tt> as well as <tt class=
"classname">std::cin</tt>, yet he/she hasn't anywhere told the
compiler that he/she means the <tt class="classname">cout</tt> and
<tt class="classname">cin</tt> of <tt class="literal">std</tt>.</p>
<p>Another matter of style is the poor way of program interaction
with its user. I'll delve deeper into that throughout the criticism
below. For the moment, however, especially for students, I say that
it is a very good practice to get used to let the user know what
the program is supposed to do. This could easily be done using a
short series of initial prompts to the user before he/she starts
the I/O process. Afterwards, let's go through the code. The first
line:</p>
<pre class="programlisting">
#include &lt;iostream.h&gt;
</pre>
<p>should be re-written as:</p>
<pre class="programlisting">
#include &lt;iostream&gt;
</pre>
<p>I say that because the Standard has allowed the header files to
be implemented with extensions other than <tt class=
"filename">.h</tt> (&sect;16.2, Phrase 5 and &sect;17.4.1.2,
Footnote 158).</p>
<p>The next line, in fact, led me into doubt. I checked the
Standard to see whether there really is such a standard header.
And, there is not. Thus</p>
<pre class="programlisting">
#include &lt;process.h&gt;
</pre>
<p>should be fully omitted. The following line</p>
<pre class="programlisting">
void main(void)
</pre>
<p>although may work under many implementations, is not portable
(&sect;3.6.1, Phrase 2 of 98 Standard).</p>
<pre class="programlisting">
int N, i, j, k;
</pre>
<p>This line should not be written here. Variables should be
declared as close as possible to where they got used. Furthermore,
as far as I can see, those variables are all supposed to hold
sizes. Therefore, it's quite irrational to prefer <tt class=
"type">int</tt> to <tt class="type">size_t</tt> for their type.
I'll again come to that as I proceed through the code.</p>
<pre class="programlisting">
double **A, **B, **C;
</pre>
<p>Assuming that the decision of playing with matrices using
<tt class="type">double**</tt>s is a good decision - which turns
out not to be so - for the mere sake of extendibility, should be
replaced by:</p>
<pre class="programlisting">
typedef double** Matrix;
Matrix A, B, C;
</pre>
<p>This way, the code will work easily by merely changing the
<tt class="literal">typedef</tt> as he/she decides to change the
data structure using which he/she wants to play with matrices.</p>
<p>Another big mistake is:</p>
<pre class="programlisting">
double sum = 0.0;
</pre>
<p>here. I'll mention in the following where it is best to do
that.</p>
<pre class="programlisting">
using std::cout;
using std::cin;
cout &lt;&lt; &quot;Dimension of Matrix? &quot; &lt;&lt; endl;
size_t N;
cin &gt;&gt; N;
</pre>
<p>As you can see, I've added statements as per what I've
previously spoken about. Another point about any input is to check
the input stream for (possible) errors. Hence:</p>
<pre class="programlisting">
if(!cin) { ... }
</pre>
<p>(Perhaps the use of some exceptions.)</p>
<pre class="programlisting">
A = new (double *) [N];
B = new (double *) [N];
C = new (double *) [N];
</pre>
<p>When you do:</p>
<pre class="programlisting">
A = new (double *);
</pre>
<p>what you get is a <span class="emphasis"><em>single</em></span>
pointer to a pointer to <tt class="type">double</tt>, and not an
<span class="emphasis"><em>array</em></span> of pointers to pointer
to <tt class="type">double</tt>. To get the latter, you need to
write what I have.</p>
<p>I tried a lot to find out why the student has come to the
observation that it works for <tt class="literal">N = 2</tt>,
whilst it does not for <tt class="literal">N = 3</tt>. The only
reasonable guess of mine is the following snippet from the Standard
(&sect;18.4.1.2, Footnote 211):</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>&quot;&hellip;The array new expression, may, however, increase the
size argument to <tt class="literal">operator new[]</tt>
(<tt class="type">std::size_t</tt>) to obtain space to store
supplemental information.&quot;</p>
</blockquote>
</div>
<p>That is, I think for <tt class="literal">N = 2</tt>, the above
space for storing supplemental information allocated invisibly by
VC++ suffices, whilst it does not suffice for <tt class="literal">N
= 3</tt>. I guess, furthermore, that for little <tt class=
"literal">N</tt>'s - which are much likely to suffice for the
student's test cases - cygwin does a similar job in allocating a
space which happens to be satisfactory.</p>
<p>Another important point, the necessity of which may not become
that obvious at academy, but somehow plays a vital role in
commercial programming, is the validation of any try for
allocation. This means that, under normal conditions such as that
of ours, any such try should be put in a <tt class=
"literal">try</tt>/<tt class="literal">catch</tt> block.</p>
<pre class="programlisting">
for(size_t i = 0; i &lt; N; ++i) {
  A[i] = new double[N];
  B[i] = new double[N];
  C[i] = new double[N];
}
</pre>
<p>Yep! That's right. I've defined <tt class="varname">i</tt>
inside the <tt class="literal">for</tt> body. The reason is what
I've already mentioned; variables should always be declared as
close to their application as possible. Furthermore, they should
not be present outside the scope they are supposed to function.</p>
<p>Anybody having a little experience of overloading in C++ knows
enough why should one always prefer the prefix <tt class=
"literal">operator ++</tt> to its postfix counterpart. Although you
may argue that, in this case, we're dealing with built-in types,
and no modern compiler may leave optimising it off, I insist on
what I told. Why? 'Cause of two important points: First, this kind
of optimisation - although quite common - is not guaranteed.
Second, it is a good practice to get used to that. Having that
done, you'll never lose efficiency whilst dealing with objects
constructing/destructing of which is much more than wasteful.</p>
<p>Again this <tt class="literal">for</tt> body should all lie in a
<tt class="literal">try</tt>/<tt class="literal">catch</tt> block.
Let's go further.</p>
<pre class="programlisting">
cout &lt;&lt; &quot;Enter matrix A: (Please enter each
         row in one line.)&quot; &lt;&lt; endl;
for(size_t i = 0; i &lt; N; ++i) {
  for(size_t j = 0; j &lt; N; ++j)
    cin &gt;&gt; A[i][j];
  cin.get();
}
</pre>
<p>There are many ways for inputting a matrix. The one chosen by
the student is not appropriate however. What's wrong with it? It
prompts something to the user each time, and asks him/her to enter
each element again and again. One plausible way seems to be that of
mine, in which I ask the user only one time about what he/she is
supposed to do. This way has got another advantage, and that's the
fact that it well equally works for when we want to input from
files. Furthermore, human beings find it much more natural as
they're working with 2 by 2 matrices. We should then check the
input stream for possible errors. The next <tt class=
"literal">for</tt> body should be replaced with a similar one like
above.</p>
<pre class="programlisting">
for(size_t i = 0; i &lt; N; ++i)
  for(size_t j = 0; j &lt; N; ++j) {
    double sum = 0.0;
    for(size_t k = 0; k &lt; N; ++k)
      sum += A[i][k] * B[k][j];
    C[i][j] = sum;
  }
</pre>
<p>That is, I've defined sum at the best possible position.
Anywhere outside this body sum would be meaningless. After a few
blank lines in output</p>
<pre class="programlisting">
cout &lt;&lt; &quot;A * B = &quot; &lt;&lt; endl;
for(size_t i = 0; i &lt; n; ++i) {
  std::copy(C[i][0], C[i][N],
    std::ostream_iterator&lt;double&gt;(cout, &quot; &quot;));
  cout &lt;&lt; endl;
}
</pre>
<p>Here, I've suited the already-at-hand tool of the Standard,
<tt class="function">std::copy()</tt>. Note that this needs the
addition of <tt class="literal">#include &lt;algorithm&gt;</tt> as
well as <tt class="literal">#include &lt;iterator&gt;</tt> at the
top of the program.</p>
<p>And another extremely important point which this student - like
many other newbies - has forgotten is to <tt class=
"literal">delete[]</tt> the allocated memory. That is:</p>
<pre class="programlisting">
for(size_t i = 0; i &lt; N; ++i) {
  delete[] A[i];
  delete[] B[i];
  delete[] C[i];
}
delete[] A;
delete[] B;
delete[] C;
</pre>
<p>And, the rest of the code which has not been included in the
journal...</p>
<p>Assuming that there is no better candidate than raw pointers, I
recommend the student to reconsider the code. Yes, the code is
quite trivial. But, it's a mixture of many different creatures. It
does its input, it constructs its own objects, it performs the
multiplication, it then outputs the resulting matrix, and finally,
it destructs the objects. These are the major steps, not? This is a
very good point showing us the necessity of splitting the code into
different functions with names indicating what's intended. Here is
what will be the result: (All the following code is off-hand. The
deadline is close, and I've got to finish the criticism. So, please
don't be fussy.)</p>
<pre class="programlisting">
int main() {
  cout &lt;&lt; &quot;This programme ...&quot;;
  cout &lt;&lt; &quot;Dimension of matrices? &quot;;
  size_t N;
  cin &gt;&gt; N;
  Matrix A, B, C;
  Construct(A, N);
  Construct(B, N);
  Construct(C, N);
  Input(A, cin);
  Input(B, cin);
  C = Multiply(A, B);
  Output(C, cout);
  Destruct(A);
  Destruct(B);
  Destruct(C);
  return 0;
}
</pre>
<p>I'm wondering whether there could ever be a guy aware of OOP,
whom the above code does not whet appetite for assembling a class -
an ADT, in other words - which serves the job much neater.</p>
<p>In fact, considering the very little code above, one should have
gotten quite sure that playing with raw pointers also very
dangerous, is very cumbersome. A well arisen question then is that
isn't there any facility in C++ which can ease the job? Oh yes,
there are. You can say use their majesty <tt class=
"classname">vector&lt;&gt;</tt>s. This way, you get rid of all the
allocation, evaluation of allocation, and deallocation stuff. All
of those bothers are now settled by the aids of automatically
served features of <tt class="classname">vector&lt;&gt;</tt>. This
way, you should end up with something like</p>
<pre class="programlisting">
int main() {
  cout &lt;&lt; &quot;Dimension? &quot;;
  Matrix&lt;double&gt;::size_type n;
  cin &gt;&gt; n ;
  Matrix&lt;double&gt; A(n), B(n), C(n);
  cout &lt;&lt; &quot;Enter A:&quot; &lt;&lt; endl;
  cin &gt;&gt; A;
  cout &lt;&lt; &quot;Enter B:&quot; &lt;&lt; endl;
  cin &gt;&gt; B;
  C = A * B;
  cout &lt;&lt; &quot;A * B = &quot; &lt;&lt; endl &lt;&lt; C;
  return 0;
}
</pre>
<p>Do you see what's happened? You've ended up with nothing apart
from the abstract problem at hand. Full stop. Wow!</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e672" id="d0e672"></a>The Winner of
SCC 32</h3>
</div>
<p>The editor's choice is:</p>
<p><span class="bold"><b>Calum Grant</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="d0e685" id="d0e685"></a>Guest
Commentary - Alan Griffiths <tt class="email">&lt;<a href=
"mailto:alan@octopull.demon.co.uk">alan@octopull.demon.co.uk</a>&gt;</tt></h2>
</div>
<p>When faced with code like this it is difficult to know where to
start - inappropriate choice of headers, ignorance of what the
standard mandates (<tt class="literal">void main()</tt>!),
anti-idiomatic usage (choice of variable names and scope, memory
management &quot;by hand&quot;), bad design and just plain bugs. There is
also the question of assessing what the student understands -
clearly suggesting writing a <tt class="classname">matrix</tt>
class won't help a student that apparently hasn't even caught onto
using functions to factor out repetitive code.</p>
<p>I'll mention the fundamental problem that often occurs with more
experienced developers: too much code has been written without
giving thought to finding out if it works. It appears that while
the student has some test input (and expected results?) against
which to run the program whole program, she is at a loss as to how
to identify which parts of the program are (or are not) working. If
the student exhibited a better knowledge of the language one might
suggest that the program be broken down into pieces. (Indeed, the
student should have been introduced to functions before this
point.)</p>
<p>However, introducing functions and user defined types is a long
road that doesn't address the immediate problem of getting the
program working in a way the student understands. And this student
has identified a prime suspect: incorrect use of <tt class=
"literal">new</tt> - C++ is unforgiving of developers that use
language features they don't understand. It is rarely the case that
arrays should be allocated using <tt class="literal">new</tt>, and
in this occasion new is not an appropriate solution. So, I'm going
to look at this code with a view to showing how <tt class=
"literal">new</tt> and all its pitfalls can be avoided.</p>
<p>First let's show the code to a compiler:</p>
<pre class="screen">
Compiling source file(s)...
main.cpp
In file included from C:\MinGWStudio\MinGW\include\
c++\3.3.1\backward\iostream.h:31,
from main.cpp:1:
C:\MinGWStudio\MinGW\include\c++\3.3.1\backward\backward_warning.h:32:2: warning: #warning This file includes at least one deprecated or antiquated header. Please consider using one of the 32 headers found in section 17.4.1.2 of the C++ standard. Examples include substituting the &lt;X&gt; header for the &lt;X.h&gt; header for C++ includes, or &lt;sstream&gt; instead of the deprecated header &lt;strstream.h&gt;. To disable this warning use -Wno-deprecated.
main.cpp:4: error: 'main' must return 'int'
main.cpp:4: error: return type for 'main' changed to 'int'
scc24.exe - 2 error(s), 1 warning(s)
</pre>
<p>Before we continue, I'll fix these problems. The header
<tt class="filename">&lt;iostream.h&gt;</tt> refers to a
pre-standard library distribution, and <tt class=
"filename">&lt;process.h&gt;</tt> is a posix header irrelevant to
the current program. Replace these with:</p>
<pre class="programlisting">
#include &lt;iostream&gt;
#include &lt;vector&gt;
</pre>
<p>The latter, <tt class="filename">&lt;vector&gt;</tt>, isn't
needed yet, but I'll use it shortly to provide a dynamically sized
array in place of the current heap allocations.</p>
<p>The remaining diagnostics indicate that the corrected signature
for <tt class="function">main</tt> is:</p>
<pre class="programlisting">
int main()
</pre>
<p>Making that change and back to the compiler:</p>
<pre class="screen">
Compiling source file(s)...
main.cpp
main.cpp: In function 'int main()':
main.cpp:10: error: 'cout' undeclared (first use this function)
main.cpp:10: error: (Each undeclared identifier is reported only once for each function it appears in.)
main.cpp:10: error: 'endl' undeclared (first use this function)
main.cpp:11: error: 'cin' undeclared (first use this function)
scc24.exe - 4 error(s), 0 warning(s)
</pre>
<p>There are several ways to fix these diagnostics. My usual
preference is to use the fully qualified names, but it will
probably confuse the student less to employ using definitions. At
the top of <tt class="function">main</tt>, add:</p>
<pre class="programlisting">
using std::cin;
using std::cout;
using std::endl;
</pre>
<p>And now we have some code that compiles - and Comeau (<a href=
"http://www.comeaucomputing.com/tryitout/" target=
"_top">http://www.comeaucomputing.com/tryitout/</a>) is happy with
it too.</p>
<p>Next, to eliminate those suspicious uses of <tt class=
"literal">new</tt> - there is a far better option - <tt class=
"classname">std::vector</tt>. Replace the declarations of
<tt class="varname">A</tt>, <tt class="varname">B</tt> and
<tt class="varname">C</tt> with aliases for <tt class=
"classname">vector</tt> and <tt class="classname">matrix</tt> types
as follows:</p>
<pre class="programlisting">
typedef std::vector&lt;double&gt; vector;
typedef std::vector&lt;vector&gt; matrix;
</pre>
<p>Finally, replace the memory allocation code with:</p>
<pre class="programlisting">
matrix A(N, vector(N));
matrix B(N, vector(N));
matrix C(N, vector(N));
</pre>
<p>Now, magically, the program works! Let's look at the whole
thing:</p>
<pre class="programlisting">
#include &lt;iostream&gt;
#include &lt;vector&gt;
int main() {
  using std::cin;
  using std::cout;
  using std::endl;
  typedef std::vector&lt;double&gt; vector;
  typedef std::vector&lt;vector&gt; matrix;
  int N, i, j, k;
  double sum = 0.0;
  cout &lt;&lt; &quot;Dimension of Matrix ?&quot; &lt;&lt; endl;
  cin &gt;&gt; N;
  matrix A(N, vector(N));
  matrix B(N, vector(N));
  matrix C(N, vector(N));
  for(i=0; i&lt;N; i++)
    for(j=0; j&lt;N; j++) {
      cout &lt;&lt; &quot;A[&quot; &lt;&lt; i &lt;&lt; &quot;][&quot; &lt;&lt; j &lt;&lt; &quot;] = ?&quot;
           &lt;&lt; endl;
      cin &gt;&gt; A[i][j];
    }
  for(i=0; i&lt;N; i++)
    for(j=0; j&lt;N; j++) {
      cout &lt;&lt; &quot;B[&quot; &lt;&lt; i &lt;&lt; &quot;][&quot; &lt;&lt; j &lt;&lt; &quot;] = ?&quot;
           &lt;&lt; endl;
      cin &gt;&gt; B[i][j];
    }
  for(k=0; k&lt;N; k++)
    for(i=0; i&lt;N; i++) {
      sum = 0.0;
    for(j=0; j&lt;N; j++)
      sum += A[i][j]*B[j][k];
    C[i][k] = sum;
  }
  cout &lt;&lt; endl &lt;&lt; endl &lt;&lt; endl;
  for(i=0; i&lt;N; i++)
    for(j=0; j&lt;N; j++)
      cout &lt;&lt; &quot;C[&quot; &lt;&lt; i &lt;&lt; &quot;][&quot; &lt;&lt; j &lt;&lt; &quot;] = &quot;
           &lt;&lt; C[i][j]&lt;&lt; endl;
}
</pre>
<p>Actually, there is still plenty wrong with this - anti-idiomatic
usage (choice of names and scope, addiction to <tt class=
"literal">std::endl</tt>), bad design and bugs. In short, it is
still suitable as an entry for a &quot;Student Code Critique&quot;! On the
other hand, the student does not appear ready to deal with these
problems (yet!) and should learn that there are easier solutions to
attempt to manage memory by hand.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e791" id="d0e791"></a>Student Code
Critique 33</h2>
</div>
<p>(Submissions to <tt class="email">&lt;<a href=
"mailto:scc@accu.org">scc@accu.org</a>&gt;</tt> by May 10th)</p>
<p>Special thanks to Richard Corden 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 <tt class="literal">true</tt> block of the
<tt class="literal">if</tt> statement where <tt class=
"literal">iter-&gt;first</tt> is not <tt class="literal">5</tt>.
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>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
