    <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</title>
        <link>https://members.accu.org/index.php/articles/1212</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 15, #2 - Apr 2003</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/c109/">152</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c183+109/">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</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 06 April 2003 13:15:57 +01:00 or Sun, 06 April 2003 13:15:57 +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>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.</p>
<p>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.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e26" id="d0e26"></a>Late Entry to
SCC 19</h2>
</div>
<p>Before providing the entries for the current competition, here
is one that arrived too late for the last one (note that
competition material goes up on www.accu.org at the time an issue
of C Vu is distributed so that those who have to wait for their C
Vu because of slow post can still compete.)</p>
<p>Unfortunately the entry was not only late but the writer forgot
to include their name in the file. Please help me give you credit
by remembering to include your name in all files you send as
attachments.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e33" id="d0e33"></a>From Anon</h3>
</div>
<p>Since this is my first time to reply to a code critique, I hope
I won't embarrass myself too badly with any blunders. I'd also just
like to say how much I enjoy getting to learn about C++ by reading
C Vu and lurking in the mailing lists. The comments below were
heavily influenced by my reading of several of my reference books,
including <i class="citetitle">Accelerated C++</i> by Koenig and
Moo, and Steve Myers' <i class="citetitle">Effective C++</i> and
<i class="citetitle">More Effective C++</i>.</p>
<p>First off, the design of the class has several flaws. In class
<tt class="classname">Card</tt>, <tt class=
"methodname">Display()</tt> is defined as a pure virtual function,
thus making <tt class="classname">Card</tt> an abstract class that
cannot be instantiated, a clear error. Also, why is the destructor
defined as virtual? From these two functions, it seems that
<tt class="classname">Card</tt> is meant to be an abstract base
class with other classes derived from it. But why? It seems that a
class representing a physical card should not need derived classes
from it, but since I am still in the beginning stages of learning
C++ and haven't learned much yet about class hierarchy design yet,
I could be mistaken. If <tt class="classname">Card</tt> is not
going to be derived from, we do not need any virtual functions. I
am thinking that the <tt class="methodname">Display()</tt> function
would be used at a later date to draw the actual card, and the
implementation of it isn't needed yet. Also, if we don't need a
virtual destructor, we can leave that out of our class, since the
compiler will auto-generate a non-virtual default destructor
anyway.</p>
<p>Next are some style concerns in the code. First off, I noticed
that <tt class="varname">RegularPack</tt> is a global variable,
which in general is not recommended. In my example, I would move
this variable into <tt class="function">main()</tt>, making it a
local variable. Second, the main code has two loops that are both
meant to index across an array. But two different end conditions
are used. One style should be used, and then adhered to make the
code more consistent. The second loop doesn't even use <tt class=
"varname">RegularPack</tt> to identify the number of times the loop
executes, just a so-called &quot;magic number&quot; which again is not
recommended. The first loop also uses the variable &quot;<tt class=
"varname">i</tt>&quot;, which is defined in <tt class=
"function">main()</tt>. Common C++ practice it to define a loop
index variable in the <tt class="literal">for</tt> header, so that
it goes out of scope and is destroyed after the loop is finished.
Third, the code uses both &quot;<tt class="literal">\n</tt>&quot; and
<tt class="literal">std::endl</tt> to insert a new line in the
output stream. A fourth inconsistency is that the naming convention
used is not consistent in that at least one variable (<tt class=
"varname">pCard</tt>) uses Hungarian notation, while all other
variables do not. For both of these, I think the best thing to do
is use one form, and be consistent. The last, and biggest style
issue in my opinion is that an array of pointers is being used to
represent a deck of cards. It seems that using <tt class=
"classname">vector&lt;Card&gt;</tt> from the standard C++ library
would be perfect to hold a number of cards. This allows us to use
the generic sorting functions in the standard library in the future
if needed, as well as not worrying about all the problems pointers
can cause (especially for us beginners).</p>
<p>Now for the compilation errors. I tried compiling the code with
Visual C++ .NET, as well as Comeau's online compiler. I added
appropriate <tt class="literal">include</tt> and <tt class=
"literal">using</tt> statements, which were not in the original
code posting. I am guessing that they were left out for brevity,
but if not then certainly this would be an error as well. The first
thing that I noticed was the typo in the first loop, where
<tt class="varname">RegularDeck</tt> should be <tt class=
"varname">RegularPack</tt>. Also, I got two warnings, one that
<tt class="varname">pCard</tt> was never used, and the second was
that &quot;label '<tt class="literal">Card:</tt>' was declared but never
referenced&quot;. The second warning is actually a syntax error in that
the &quot;<tt class="literal">Card:</tt>&quot; shouldn't be there. The next
error was the last line of the program, where no variable
<tt class="classname">Card</tt> was defined. The last error was for
the body of the second loop. To be honest, after the first loop,
which just gives each Card in the array a value from zero to 53, I
don't understand what the code is supposed to do. The second loop
(I think) is meant to index through the array, and display each
<tt class="classname">Card</tt>'s value. But the second line in the
loop body is all wrong, since the pointer shouldn't be deferenced,
and even when you fix that, <tt class="function">SetNumber</tt>
returns <tt class="literal">void</tt>, which is an illegal type to
pass to <tt class="classname">cin</tt>.</p>
<p>I've rewritten the class <tt class="classname">Card</tt> so that
it no longer has a <tt class="methodname">Display()</tt> function,
which wasn't used anyway, as well as leaving out a destructor, and
letting the compiler generate one when needed. I've added
appropriate include and using statements. In <tt class=
"function">main()</tt>, I've used a <tt class=
"classname">vector&lt;Card&gt;</tt> to represent the deck, and use
the standard library functions to insert and view the values of the
deck. The program gives each of the 54 cards a value, from zero to
53, then prints out each card and its value. I'm sure there is a
better way to re-write the code, but as I am still learning, I'm
just trying to keep it simple, and (hopefully) correct.</p>
<pre class="programlisting">
#include&lt;iostream&gt;
#include&lt;vector&gt;
using namespace std;
class Card {
public:
  Card():itsNumber(0) {}
  Card (int Number):itsNumber (Number) {}
  void SetNumber (int val) {itsNumber = val;}
  int GetNumber () const {return itsNumber;}
private:
  int itsNumber;
};

int main() {
  const int RegularPack = 54;
  vector&lt;Card&gt; Pack;
  for (int i=0; i &lt; RegularPack; ++i) 
    Pack.push_back(i);
  for (vector&lt;Card&gt;::size_type i = 0; 
       i != Pack.size(); ++i)
    cout &lt;&lt; &quot;Card number &quot; &lt;&lt; i 
         &lt;&lt; &quot; value is &quot; 
         &lt;&lt; Pack[i].GetNumber() &lt;&lt; endl;
}
</pre></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e153" id="d0e153"></a>Student Code
Critique 20</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e156" id="d0e156"></a>The Code</h3>
</div>
<p>The problem this time was to help this student within the terms
he specifies. However you should take the opportunity to correct
errors and misconceptions.</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>I am trying to write a function that dynamically allocates an
array of integers. The function should accept an integer argument
indicating the number of elements to allocate. The function should
perform necessary error-checking to determine if the memory was
successfully allocated. if the memory was allocated the function
should return a pointer to it. Otherwise it should return a null
pointer.</p>
<p>This is &quot;Homework&quot; so I do not wish to have the program written
for me. My problem at this point is that I am having trouble coming
up with the concepts in my head. Any help would be appreciated.
This is what I have so far.</p>
<pre class="programlisting">
#include &lt;iostream&gt;
using namespace std;
//function prototypes
int *allocatemem(int);
int *sortNums(int);

void main(void) {
  int NoGrades;
  int *grades;
  int *test;
  cout &lt;&lt; 'Number of grades to enter: ';
  cin &gt;&gt; NoGrades;
  grades = allocatemem(NoGrades);
  for(int i=0; i&lt;NoGrades; i++); {
    cout&lt;&lt;'What is test score # '
        &lt;&lt; (i+1) &lt;&lt;' ?';
    cin&gt;&gt; *(test +i);
    if(*(test +i) &lt; 0) {
      cout &lt;&lt; 'Must be positive \n';
      cout&lt;&lt;'Please enter Test #'
          &lt;&lt; (i+1) &lt;&lt;' correctly: \n';
      i-;
    }
  }
  sortNums(NoGrades);
}
int allocatemem (int amount) {
  int *memory;
  memory = new int[amount];
  if(memory != 0) {
    cout &lt;&lt; 'We have memory \n';
    cout &lt;&lt; 'going back to main \n';
    return memory;
  }
  cout &lt;&lt; 'We do not have enough memory for'
          'this task \n';
    cout &lt;&lt; 'going back to main \n';
    return memory;
}
int sortNums(int scores) {
  for(int j=0; int temp=0; i&lt;numberOfScores; j++)
    temp= *(test +1);
    if(*(test + 1) &lt; * test +1 + 1) {
      *(test +1)= *(test +i +1)
      *(test + i + 1) = temp
    }
  for(int a = 0; a&lt;numberOFScores; a++)
    cout&lt;&lt;*(test + 1)&lt;&lt;' ';
}
</pre></blockquote>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e168" id="d0e168"></a>From Catriona
O'Connell <tt class="email">&lt;<a href=
"mailto:catriona38@hotmail.com">catriona38@hotmail.com</a>&gt;</tt></h3>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e173" id="d0e173"></a>Major errors in
the student's code:</h4>
</div>
<p>While space is allocated for grades, the marks are actually read
into <tt class="varname">test</tt>, which is an uninitialised
pointer - leading to overwriting of storage. Pointers should be
initialised before they are dereferenced.</p>
<p>The function <tt class="function">allocatemem()</tt> is declared
to return <tt class="type">int*</tt>, but the definition returns
<tt class="type">int</tt>.</p>
<p>Nothing is done with the return code from <tt class=
"function">allocatemem</tt> except to print a message. The code
continues regardless of the success or failure of the allocation
request. Actions need to be taken on return codes. As written, the
code in <tt class="function">allocatemem</tt> will not behave as
the student expects if it is compiled with a conformant compiler.
If new fails to allocate storage, it is required to throw a
<tt class="exceptionname">std::bad_alloc</tt> exception
(3.7.3.1/3). To return a null pointer instead of an exception the
user should call the <tt class="literal">nothrow</tt> variant of
<tt class="literal">new</tt>. The <tt class=
"filename">&lt;new&gt;</tt> header must be included. At this point
it is worth noting that the program does not free the allocated
storage on exit. It is good practice to free-up dynamically
acquired storage. Not all environments will clean-up after the
program terminates. I'm thinking of some subpools in the MVS OS
here.</p>
<p>In the function <tt class="function">sortnums()</tt>, there is
no good reason to declare temp in the <tt class=
"literal">for()</tt> and even if you did it should have been
separated from <tt class="literal">int j=0</tt> by a comma not a
semicolon. The <tt class="literal">for()</tt> loop as written has
four statements instead of three. The <tt class=
"function">sortnums</tt> function doesn't sort the numbers either
and there is a typo where <tt class="varname">i</tt> has been
written as 1.</p>
<p>The argument is <tt class="literal">int scores</tt> which is
never used and the loop goes over <tt class=
"varname">numberOfScores</tt> which is not defined anywhere - and
even worse has two different spellings. The function needs an
argument that defines the number of elements in the array. It is
also defined to return an integer, but declared to return a pointer
to an integer. The whole function is a mess and should be
re-written.</p>
<p>The function <tt class="function">main()</tt> should have been
declared as <tt class="literal">int main()</tt> not <tt class=
"literal">void main(void)</tt>. The C++ standard allows only
<tt class="literal">int main()</tt> and <tt class="literal">int
main(int argc, char *argv[])</tt> as definitions (3.6.1/2).</p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e257" id="d0e257"></a>Other comments
on the student's code:</h4>
</div>
<p>There is no checking of user input. As a general rule input from
a user should always be checked for validity. The coding of
<tt class="classname">cin</tt> to retrieve values from the user is
too trusting. If a user enters a non-integer value then the
stream's fail bit will be set and the <tt class=
"classname">cin</tt> object becomes unusable. One solution is to
call the <tt class="methodname">clear</tt> member to reset the fail
bit. This should be followed by the <tt class=
"methodname">ignore</tt> member to discard any additional input
from the stream.</p>
<p>Another minor flaw with the grade input code is that the student
tampers with the loop control variable to handle incorrect input.
While tampering with a loop control variable is not explicitly
forbidden by the standard it is a sign of a poor program design.
While not true in this case, there is a danger of such practices
breaking the conditional test in the <tt class="literal">for()</tt>
header.</p>
<p>The variable <tt class="varname">NoGrades</tt> is poorly named
as it might be taken to mean that the student has no grades rather
than holding the number of grades. Good naming standards are
helpful to code maintainers.</p>
<p>The student has enclosed string literals in single quotes rather
than double quotes in his/her dialogue with the user. Also as a
matter of style, if <tt class="classname">cin</tt> and <tt class=
"classname">cout</tt> are being used it would be more consistent to
use <tt class="literal">std::endl</tt> rather than <tt class=
"literal">'\n'</tt> as a newline<sup>[<a name="d0e298" href=
"#ftn.d0e298" id="d0e298">1</a>]</sup>.</p>
<p>It is also not beneficial to use the pointer notation for the
<tt class="varname">test</tt> array, when the array[subscript]
format would have been clearer. There is an equivalence between
<tt class="literal">*(test +i)</tt> and <tt class=
"literal">test[i]</tt>, but the latter is easier to visualise -
especially if you are a Fortran programmer :-)</p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e316" id="d0e316"></a>Comments on my
alternative code:</h4>
</div>
<p>The pointer returned from <tt class=
"methodname">allocatemem</tt> is used to determine if the code
proceeds with data processing or drops through to the final return.
This removes the need to have multiple return points.</p>
<p>The <tt class="function">getInput()</tt> function addresses the
problems raised by the student's use of <tt class=
"classname">cin</tt> to retrieve input from the user. The
<tt class="function">getInput</tt> function requires that a valid
range of input values be passed as arguments so that the user is
required to enter a valid data type within the specified range. The
<tt class="function">getInput()</tt> function is a specialisation
of the template code presented in response to SCC12.</p>
<p>I have snaffled a <tt class="function">bubblesort()</tt> routine
from <a href=
"http://leepoint.net/notes/cpp/algorithms/arrayfuncs/bubblesort2.html"
target=
"_top">http://leepoint.net/notes/cpp/algorithms/arrayfuncs/bubblesort2.html</a><sup>[<a name="d0e345"
href="#ftn.d0e345" id="d0e345">2</a>]</sup>. The bubble sort
routine is adequate for small amounts of input and is simple to
understand and implement. The bubblesort routine sorts the array in
place. The student did not specify what we were to do with the
output, so I printed it just to demonstrate that the sort
worked.</p>
<pre class="programlisting">
#include &lt;iostream&gt;
#include &lt;new&gt;
#include &lt;climits&gt;
using namespace std;
int *allocateMem(int);
void bubblesort(int *, int);
void getInput(const char *, int&amp;, int, int);
int main(){
  int numGrades;
  int *grades;
  int i;
  getInput(&quot;Number of grades? &quot;, numGrades, 1, 10);
  grades = allocateMem(numGrades);
  if(grades){
    for(i=0; i&lt;numGrades; ++i){
      getInput(&quot;Enter Grade&quot;, grades[i], 0, 100);
    }
    bubblesort(grades, numGrades);
    for (i=0; i&lt;numGrades; ++i){
      cout &lt;&lt; grades[i] &lt;&lt; endl;
    }
    delete [] grades;
  }
  return 0;
}


int *allocateMem(int amount){
  int *memory;
  memory = new(nothrow) int[amount];
  if(!memory){
    cout &lt;&lt; &quot;Error: Unable to allocate sufficient &quot;
         &lt;&lt; &quot;memory.&quot; &lt;&lt; endl;
    cout &lt;&lt; &quot;Program terminating.&quot; &lt;&lt; endl;
  }
  return memory;
}

void bubblesort(int *x, int n){
// code suppressed use std::sort instead - Francis
}

void getInput(const char *prompt, int&amp; r, int lower, int upper){
  bool error;
  do{
    cout &lt;&lt; prompt &lt;&lt; &quot;: &quot; &lt;&lt; flush;
    error = !((cin &gt;&gt; r) &amp;&amp; (r &gt;= lower)
                         &amp;&amp; (r &lt;= upper));
    if(error){
      cout &lt;&lt; &quot;Please try again.&quot; &lt;&lt; endl;
      cout &lt;&lt; &quot;Enter an integer between &quot; &lt;&lt; lower
           &lt;&lt; &quot; and &quot; &lt;&lt; upper &lt;&lt; endl;
    }
    cin.clear();
    cin.ignore(INT_MAX,'\n');
  } while(error);
}
</pre></div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e354" id="d0e354"></a>From Roger Orr
<tt class="email">&lt;<a href=
"mailto:rogero@howzatt.demon.co.uk">rogero@howzatt.demon.co.uk</a>&gt;</tt></h3>
</div>
<p>Dear student,</p>
<p>First the good news - most of your difficulty in solving the
problem doesn't seem to be with the concepts. The bad news is you
seem to have several sorts of problems, mostly with the syntax -
that is the details of writing C++ code.</p>
<p>Let's deal with this systematically.</p>
<p>Firstly, the problem you were set was to write a function to
allocate memory and return it, or null on failure. Your <tt class=
"function">allocatemem</tt> function almost does this (apart from a
small syntax error). However you have allocated the memory with new
and in standard C++ this does not return at all if it fails but
throws an exception. However you were asked to check for out of
memory and return null. Perhaps the teacher was asking the wrong
question? I'll leave it to you to discuss that with them!</p>
<p>So you need to use a different 'flavour' of new to get back a
null pointer if there isn't enough memory. This is done by adding
an extra argument to <tt class="literal">new</tt> and writing
'<tt class="literal">new(nothrow)</tt>' instead.</p>
<p>That solves the main conceptual error you seem to have with the
problem set you. The second error is you forgot to check the return
value when you call <tt class="function">allocatemem</tt> in
<tt class="function">main</tt>. If it failed then you'd better stop
there!</p>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e386" id="d0e386"></a>Syntax, syntax,
syntax.</h4>
</div>
<p>You have a few syntax problems - perhaps you were in a hurry?
&quot;More haste less speed&quot; when it comes to syntax errors I'm
afraid.</p>
<p>Firstly, C++ is fussy about the difference between a single and
a double quote: ' and &quot;; some other languages don't care. A single
quote is for a single character, a double quote is for a string of
characters. As it happens all your single quotes can be changed to
double quotes.</p>
<p>Secondly, C++ is fussy about referring to variables in other
functions. So <tt class="function">sortNums</tt> tries to use the
variable test from <tt class="function">main</tt> but it can't see
it - you need to pass this variable in as another parameter to the
function.</p>
<p>Incidentally, <tt class="function">sortNums</tt> is perhaps not
the best name for the function since it does two jobs - it sorts
the numbers but then prints them. I'd prefer writing two functions,
<tt class="function">sortNums</tt> and <tt class=
"function">printNums</tt>, and so keeping code that changes the
scores separate from code that prints them. You can then make the
array constant in the <tt class="function">printNums</tt> function
that among other things prevents you accidentally writing code
which changes it.</p>
<p>Thirdly, you aren't consistent and, alas, the compiler expects
you to be completely consistent. It is also easier for you and
everybody else if you use consistent names for things. For example,
the number of grades in the program is called many names:
<tt class="varname">NoGrades</tt>, <tt class="varname">grades</tt>,
<tt class="varname">numberOfScores</tt> and <tt class=
"varname">numberOFScores</tt> in various parts of your code. You
also have <tt class="varname">grades</tt> and <tt class=
"varname">test</tt> both referring to the same data.</p>
<p>Try to ensure that the names of variables are always the same -
and this includes being in the same case. To make this consistency
easier it is a good idea to adopt a simple policy on names - many
people use a mixed case with first letter lower case like you have
in <tt class="varname">numberOfScores</tt>. I've picked on one name
and used it consistently in the program.</p>
<p>Another place where you must be consistent is that the types
used for function returns and arguments must be the same in the
function prototype and where the function is actually defined. The
prototype for <tt class="function">sortNums</tt> returns <tt class=
"type">int*</tt> but the function itself claims to return
<tt class="type">int</tt>.</p>
<p>Lastly you have a small problem with the <tt class=
"literal">for</tt>-loop in <tt class="function">sortNums</tt> - you
can initialise multiple variables in the <tt class=
"literal">for</tt>-loop initialiser but if so you must separate
them with commas. In your case I'd simple remove <tt class=
"literal">int temp=0;</tt> completely and put the <tt class=
"type">int</tt> on the next line to declare and define <tt class=
"varname">temp</tt> in one go.</p>
<p>All being well you now have a body of code that compiles and
does solve the problem you were set.</p>
<p>However we are not finished yet...compiling is not at all the
same thing as working! It would be nice if your sample program
worked and used standard C++.</p>
<p>Firstly, <tt class="function">main</tt> is defined as <tt class=
"type">void</tt> which many compiler still accept but it is an old
usage. In standard C++ <tt class="function">main</tt> always
returns an <tt class="type">int</tt>. You shouldn't need to put in
a <tt class="literal">return</tt>-statement in <tt class=
"function">main</tt>, the compiler ought to do this for you, but
not all compilers do so put a <tt class="literal">return 0;</tt>
just before the closing brace to be safe.</p>
<p>Secondly, <tt class="function">sortNums</tt> is defined to
return an <tt class="type">int</tt> but doesn't return anything -
and its return value is ignored where it is used! So I'd change
<tt class="function">sortNums</tt> to return <tt class=
"type">void</tt>.</p>
<p>Thirdly, you have a very, very small loop. The <tt class=
"literal">for</tt>-loop in <tt class="function">main</tt> has a
spurious ';' which the compiler understands to mean 'do nothing'
each time round the loop. Just remove it and then the loop will
work as you expect.</p>
<p>And then lastly <tt class="function">printNums</tt> doesn't
print and <tt class="function">sortNums</tt> doesn't sort! The
<tt class="literal">for</tt>-loop in <tt class=
"function">printNums</tt> uses '<tt class="literal">test + 1</tt>'
inside the loop where you wanted '<tt class="literal">test +
a</tt>'.</p>
<p>The sort is just broken but it is easily fixed. The solution
here is to stop re-inventing the wheel. The problem didn't ask you
to write a sort algorithm, so don't. Just use the standard library
sort from the header <tt class=
"filename">&lt;algorithm&gt;</tt>.</p>
<p>The final code looks like this:-</p>
<pre class="programlisting">
#include &lt;iostream&gt;
#include &lt;algorithm&gt;
using namespace std;

// function prototypes
int *allocatemem(int);
void sortNums(int* grades, 
              int numberOfGrades);
void printNums(const int* grades, 
               int numberOfGrades);

int main(void) {
  int numberOfGrades;
  int *grades;
  cout &lt;&lt; &quot;Number of grades to enter: &quot;;
  cin &gt;&gt; NoGrades;
  grades = allocatemem(numberOfGrades);
  if(grades == 0)return 1;
  for(int i=0; i&lt;numberOfGrades; i++) {
    cout &lt;&lt; &quot;What is test grade # &quot;
         &lt;&lt; (i+1) &lt;&lt; &quot; ?&quot;;
    cin &gt;&gt; *(grades +i);
    if(*(grades +i) &lt; 0 ) {
      cout &lt;&lt; &quot;Must be positive \n&quot;;
      cout &lt;&lt; &quot;Please enter Test #&quot;
           &lt;&lt; (i+1) &lt;&lt; &quot; correctly: \n&quot;;
      i-;
    }
  }
  sortNums(grades, numberOfGrades);
  printNums(grades, numberOfGrades);
  return 0;
}

int *allocatemem(int amount) {
  int *memory;
  memory = new(nothrow) int[amount];
  if(memory != 0 ) {
    cout &lt;&lt; &quot;We have memory \n&quot;;
    cout &lt;&lt; &quot;going back to main \n&quot;;
    return memory;
  }
  cout &lt;&lt; &quot;We do not have enough memory for &quot;
          &quot;this task \n&quot;;
  cout &lt;&lt; &quot;going back to main \n&quot;;
  return memory;
}

void sortNums(int* grades, int numberOfGrades) {
  std::sort(grades, grades+numberOfGrades);
}

void printNums(const int* grades, int numberOfGrades) {
  for(int a = 0; a&lt;numberOfGrades; a++)
    cout &lt;&lt;*(grades + a)&lt;&lt;' ';
}
</pre></div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e549" id="d0e549"></a>From William
Fishburne <tt class="email">&lt;<a href=
"mailto:william.Fishburne@verizon.net">william.Fishburne@verizon.net</a>&gt;</tt></h3>
</div>
<p>The restrictions requested by the student strongly limit what
can be said. I have constrained the analysis to the <tt class=
"function">allocatemem</tt> function, as requested, but in a normal
circumstance, it would be worthwhile to discuss the whole
program!</p>
<p>A few overriding things need to be addressed, within the
limitation of discussing this one function, these still apply:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p><tt class="literal">using namespace std;</tt> is a bad
practice<sup>[<a name="d0e567" href="#ftn.d0e567" id=
"d0e567">3</a>]</sup>. It is better to specify std:: before the
items you need from the standard namespace. You probably got this
from your text, but the author also probably makes some statement
about how you shouldn't really use it and that he is doing so in
the interest of clarity. Some clarity, huh? A large reason for a
namespace is to prevent a name clash. While this little program
does not really incorporate enough to generate such a clash, why
would you risk it? Wouldn't it be better to get in the habit of
using namespaces properly so that you never have to try and debug
something where somebody got clever and used cout in their own
namespace?</p>
</li>
<li>
<p><tt class="function">main</tt> always returns an <tt class=
"type">int</tt>. Setting its return value to <tt class=
"type">void</tt> is simply an error.</p>
</li>
<li>
<p>It strikes me as very odd that a C++ class would require you to
write a function that dynamically allocates arrays. It is certainly
possible, but it is counter-intuitive to the flexibility that the
standard library offers. At the risk of pointing you in the wrong
direction, consider a <tt class="classname">multi-map</tt> from the
standard library that has built-in the ability to associate a score
with a test and to sort the result.</p>
</li>
<li>
<p>Globals are dangerous. It is much better to pass what is needed
to each function as the values are needed. This is true because a
global variable can be changed anywhere in the program. The bigger
the program, the more likely that any change will break something
else.</p>
</li>
<li>
<p>It is a big mistake to change the value of a control variable in
a <tt class="literal">for</tt>-loop. Is there another way you can
make sure that a valid test grade is entered that wouldn't require
you to decrement the control variable? (Francis, since you have
talked about C++ standards before, wouldn't it be nice if a
<tt class="literal">for</tt>-loop variable in a for loop was a
constant <span class="emphasis"><em>within</em></span> the loop?
This would sort of be a reverse sense of scope, it could only be
changed outside the loop block... Similarly, I think it makes sense
<tt class="literal">for</tt>-loop variables to never be
instantiated outside the loop statement&hellip;</p>
<i><span class="remark">Actually I strongly disagree and changing
the rule would break a good deal of existing, well-designed,
code.</span></i></li>
</ol>
</div>
<p>Now, because I respect the heck out of Francis (HEY! That is not
butt-kissing, that is the honest truth&hellip;), I downloaded
Quincy et al and typed this program into it. What do you know? The
first error that came up was the problem with <tt class=
"function">main</tt>.</p>
<p>Once I fixed my typos and a couple of obvious errors (I spare
you as per your request), the next error that came up was the
redefinition of <tt class="function">allocatemem</tt>. As a
prototype, you define it as <tt class="type">int *</tt>, then when
you define the function itself you use <tt class="type">int</tt>.
Certainly you must have meant the former as you plan to return a
pointer to an integer, right? The compiler catches simple errors
like this quite readily and it is worth working to make sure that
your program compiles before seeking other help if you can. The
listing below shows a version of your program that will compile
(wait to look at it until you have managed to get it to compile
yourself). If you attempt to run this program, you will find that
it does not work (as you expected or you would not have submitted
it). This is not unusual. Few programmers can write a program that
both compiles and runs correctly on the first try (I've never met
one).</p>
<p>OK, we have <tt class="function">allocatemem</tt> returning a
pointer to an array of integers. We accept in the number of
elements in the array. You have correctly formulated the call to
new and memory will be allocated to the pointer <tt class=
"varname">memory</tt> if it is available. What does <tt class=
"literal">new</tt> do, however, if the memory is not available? In
the C++ standard, new is supposed to throw the error message
<tt class="exceptionname">std::bad_alloc</tt>. To catch this error
message, you would need to encompass your call to new in a
<tt class="literal">try</tt>/<tt class="literal">catch</tt> clause.
In order to catch this error, you will have to include the
<tt class="filename">&lt;new&gt;</tt> header at the top of your
program.</p>
<p>There is a <tt class="literal">nothrow</tt> version of new which
returns a <tt class="literal">NULL</tt> pointer. I think it is
worth taking the time to get to know the <tt class=
"literal">try</tt>/<tt class="literal">catch</tt> clauses instead
of using the <tt class="literal">nothrow</tt> version, but let us
assume, for the moment, that you do decide to go ahead and use the
<tt class="literal">nothrow</tt> version. Are <tt class=
"literal">NULL</tt> and <tt class="literal">0</tt> the same thing?
If so, why have two different names? Consider, are <tt class=
"literal">NULL</tt> and <tt class="literal">0.0</tt> the same? I am
not asking whether <tt class="literal">NULL</tt> and <tt class=
"literal">0</tt> can be the same, but whether they are required to
be the same.</p>
<p>Finally, with regard to allocatemem, does your program pay
attention to the return value from <tt class=
"function">allocatemem</tt>? If not, why not? What will happen if
memory isn't properly allocated?</p>
<p>Some questions to consider on the rest of the program:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>What should <tt class="function">sortNums</tt> return? Does
it?</p>
</li>
<li>
<p>When printing an array, if you get the same value over and over,
then you are either not incrementing across the array or you are
not incrementing your array index.</p>
</li>
<li>
<p>What happens if you look one position past the end of an array?
How can you make sure this doesn't happen?</p>
</li>
<li>
<p>How many times should a bubble sort iterate?</p>
</li>
<li>
<p>Why does C++ allow you to reference arrays as <tt class=
"literal">grades[6]</tt> instead of requiring you to write
<tt class="literal">*(grades+6)</tt>? Is <tt class=
"literal">grades[1]</tt> always the same as <tt class=
"literal">*(grades+1)</tt>?</p>
</li>
<li>
<p>When is it appropriate to have two variables in a <tt class=
"literal">for</tt>-loop? Is your use appropriate?</p>
</li>
<li>
<p>What is the first value of <tt class="varname">test</tt>? Does
<tt class="varname">test</tt> ever change? What are the
implications for the first two values of <tt class=
"varname">temp</tt>?</p>
</li>
<li>
<p>How many integers do you pass to <tt class=
"function">sortNums</tt>?</p>
</li>
<li>
<p>What happens when memory is allocated and never deleted? Where
is the best place to delete the new memory you have created?</p>
</li>
</ol>
</div>
<pre class="programlisting">
#include &lt;iostream&gt;
using namespace std;
// function prototypes
int *allocatemem(int);
int sortNums(int);
// global variables
int *grades;
int *test;

int main() {
  int NoGrades;
  cout &lt;&lt; &quot;Number of grades to enter: &quot;;
  cin &gt;&gt; NoGrades;
  grades = allocatemem(NoGrades);
  for(int i=0; i &lt; NoGrades; i++) {
    cout &lt;&lt; &quot;What is test score # &quot;
         &lt;&lt; (i+1) &lt;&lt; &quot; ?&quot;;
    cin &gt;&gt; *(test+i);
    if(*(test+i) &lt; 0) {
      cout &lt;&lt; &quot;Must be positive\n&quot;;
      cout &lt;&lt; &quot;Please enter Test #&quot;
           &lt;&lt; (i+1) &lt;&lt; &quot; correctly: \n&quot;;
      i-;
    }
  }
  sortNums(NoGrades);
  return(0);
}

int *allocatemem (int amount) {
  int *memory;

  memory = new int[amount];
  if(memory != 0) {
    cout &lt;&lt; &quot;We have memory\n&quot;;
    cout &lt;&lt; &quot;going back to main\n&quot;;
    return memory;
  }
  cout &lt;&lt; &quot;We do not have enough memory for &quot;;
  cout &lt;&lt; &quot;this task.\n Returning to main\n&quot;;
  return memory;
}

int sortNums(int numberOfScores) {
  for(int j=0, temp=0; j&lt;numberOfScores; j++) {
    temp=*(test+1);
    if(*(test+1) &lt; *(test + 1 + 1)) {
      *(test + 1) = *(test +j1 + 1);
      *(test + j + 1) = temp;
    }
  }
  for(int a=0; a&lt;numberOfScores; a++)
    cout &lt;&lt; *(test + 1) &lt;&lt; ' ';
}
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e752" id="d0e752"></a>The Winner of
SCC 20</h3>
</div>
<p>The editor's choice is: Roger Orr.</p>
<p>Please email <tt class="email">&lt;<a href=
"mailto:francis.glassborow@ntlworld.com">francis.glassborow@ntlworld.com</a>&gt;</tt>
to arrange for your prize.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e762" id="d0e762"></a>Student Code
Critique 21 (C source)</h2>
</div>
<p>The original code for this program was in C++ but I have
converted it to C because it was conceptually a C program using C++
for I/O. You will need to make an assumption about the input that
is actually causing a problem - think of an input that has many
digits. However there are several other immediate problems with the
code as well as a general design error. Can you improve the design
on the basis that the writer knows about for-loops but not about
arrays?</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e767" id="d0e767"></a>The problem</h3>
</div>
<div class="blockquote">
<blockquote class="blockquote">
<p>I'm creating a program that inputs three integers, and returns
the sum, product, average, largest and smallest. Very simple, but
I'm getting a bad return on one of my variables. Except for my
&quot;largest&quot; variable, the others are returning the correct numbers.
I'm hoping that someone can tell me where I'm going wrong.</p>
<pre class="programlisting">
#include &lt;stdio.h&gt;

int main(){
  int num1, num2, num3, sum, average
  int product, smallest, largest;
  puts(&quot;Input three different integers: &quot;);
  scanf(&quot;%d, %d, %d&quot;,&amp;num1,&amp;num2,&amp;num3);
                      // read three integers
  sum = num1 + num2 + num3;
  average = ((num1 + num2 + num3)/ 3 );
  product = num1 * num2 * num3;
  if(num1 &lt; num2 ) smallest = num1;
  if(num2 &lt; num1 ) smallest = num2;
  if(num3 &lt; smallest ) smallest = num3;
  if(num1 &gt; num2 ) largest = num1;
  if(num2 &gt; num1 ) largest = num2;
  if(num3 &gt; largest ) largest = num3;
  printf(&quot;\nSum is %d&quot;,sum);
  printf(&quot;\nAverage is %d&quot;,average);
  printf(&quot;\nProduct is %d&quot;,product);
  printf(&quot;\nSmallest is %d&quot;,smallest);
  printf(&quot;\nLargest is %d\n&quot;,largest);
  return 0;
}
</pre></blockquote>
</div>
</div>
</div>
<div class="footnotes"><br>
<hr class="c3" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e298" href="#d0e298" id=
"ftn.d0e298">1</a>]</sup> Actually many experts would not agree.
<tt class="literal">std::endl</tt> should only be used where you
require the output be flushed in addition to including a
newline.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e345" href="#d0e345" id=
"ftn.d0e345">2</a>]</sup> And I suppressed it because this is not
one of the rare places where a bubblesort offers any advantage, and
in the context of this problem the student should simply use
<tt class="classname">std::sort</tt>.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e567" href="#d0e567" id=
"ftn.d0e567">3</a>]</sup> Many would disagree with that assertion,
particularly with regards to student code.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
