    <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/1193</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 14, #4 - Aug 2002</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/c113/">144</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c183+113/">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 August 2002 13:15:54 +01:00 or Tue, 06 August 2002 13:15:54 +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="d0e13" id="d0e13"></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">Note that 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="d0e24" id="d0e24"></a>Student Code
Critique 16: The Entries</h2>
</div>
<p>You were asked to write a response to the author of the code
below in which you try to identify the causes of his/her
difficulties. Of course straightforward bugs had to be dealt with
as well.</p>
<pre class="programlisting">
#include&lt;stdio.h&gt; 
void count_up(int start, int end, int step) {
  printf(&quot;enter the upper limit&quot;);
  scanf(%d; &amp;start)
  printf(&quot;enter your lower limit&quot;);
  scanf(%d; end);
  printf(&quot;enter step size&quot;);
  scanf(%d; step)
  int x;
  for(x=start; x&lt;=finish;x=x+step) {
    printf(&quot;\n %d&quot;,x);
  }
}
int main() {
  count_up(1, 10, 1);
  count_up(-10, 10, 2);
  return 0;
}
</pre>
<p class="c2"><span class="remark">I only had two entries. Well let
me rephrase that; I can only find two entries though I have a nasty
feeling that I have lost one. In addition I have a late
contribution for the previous competition. That one raises the
problem of the time it sometimes takes for C Vu and Overload to
reach some members. Of course it mostly does not matter. However
this is one column where timeliness is important. I will see if we
can persuade our webmaster to place each competition item on our
website so that everyone can fetch it from there even if their
issue of C Vu is late. Which reminds me, it might help if our
website listed the current issue numbers for both C Vu and
Overload. Francis</span></p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e34" id="d0e34"></a>From David
Caabeiro <tt class="email">&lt;<a href=
"mailto:dac@globalmente.com">dac@globalmente.com</a>&gt;</tt></h3>
</div>
<p>[<i><span class="remark">Please note that David is not a native
English speaker. I have done some copy editing but only to help his
text flow more smoothly. Francis</span></i>]</p>
<p>There are several things to point out. First I'll discuss the
ones I consider most important.</p>
<p>The student seems to have some misunderstanding regarding
function parameters, so I'll try to explain some vocabulary.</p>
<p>When calling a function, you pass it a certain number of
<span class="bold"><b>argument</b></span>s, which are values the
function will work with while executing. When a function is
finished, you typically get back a return value (for those with
some mathematical background, this is somewhat equivalent to a
scalar field).</p>
<p>How do you create a function? First you have to introduce an
identifier to the compiler. This is called a <span class=
"bold"><b>declaration</b></span>, and its purpose is telling the
compiler what the function looks like. This way, it will be able to
check it is used correctly [0]. But this is not enough, you still
need to code the function itself and get the storage necessary to
hold it. This is called a <span class=
"bold"><b>definition</b></span>.</p>
<p>So how do you declare a function? Simple, you just specify the
function name, the parameter list type, and the return type. For
example, suppose we want a function that given the (x, y, z)
coordinates in space it returns the distance from the origin (yes,
this is a scalar field). This function could have three parameters
(for each coordinate) and return a value (the distance). So we
could declare it:</p>
<pre class="programlisting">
double dist(double x, double y, double z);
</pre>
<p>The first keyword is the return value: a double. The parameters
are enclosed in parentheses after the function name, separated by a
comma. The semicolon indicates the end of the statement. The
parameter names are optional, so a valid declaration could also
be:</p>
<pre class="programlisting">
double dist(double, double, double);
</pre>
<p>But as you may note, sometimes it's not easy to guess what the
parameters are used for.</p>
<p>A function definition is similar to a declaration, except that
it has a group of statements enclosed in braces. So in our previous
example, a possible definition could be something like this:</p>
<pre class="programlisting">
double dist(double x, double y, double z) {
  return sqrt(x * x + y * y + z * z);
}
</pre>
<p>Note that this time you do have to specify an identifier for
each parameter, which will have automatic storage duration [1].
Also note that since the braces replace a statement or group of
statements, there's no need for a semicolon. [<i><span class=
"remark">a semi-colon before the opening brace would be wrong
because the compiler would treat that as ending a declaration. One
after the closing brace would also be a technical error because it
does not meet the requirements of the grammar of either C or
C++.</span></i>]</p>
<p>Now we can take a look at the code and point out the most
evident mistakes.</p>
<p>First of all, there's a missing closing brace at the end of
<tt class="function">main()</tt> (don't know if this was a real
mistake or a printing failure). Inside <tt class=
"function">count_up()</tt>, there's a missing '<tt class=
"literal">;</tt>' at the first and last call to <tt class=
"function">scanf()</tt>, to indicate the end of a statement. Also,
the calls to <tt class="function">scanf()</tt> are incorrect, as
its prototype is</p>
<pre class="programlisting">
int scanf(const char * restrict format, ...); //[2]
</pre>
<p>where the variable argument list represents the addresses of the
objects to receive the converted input. So a call should have the
form:</p>
<pre class="programlisting">
scanf(&quot;%d&quot;, &amp;var);
</pre>
<p>Note the use of the comma to separate the parameters, and the
&amp; operator to pass the address of the object.</p>
<p>There's also some inconsistency between the messages shown and
where these values are stored (for example, the upper limit is
stored in a variable called <tt class="varname">start</tt>).
Finally, there's an identifier that was not declared: <tt class=
"varname">finish</tt>, probably meant to be <tt class=
"varname">end</tt>.</p>
<p>Now let's see the basic misconception the student is making. He
correctly declared a function with three parameters. But then he
reassigns all of them with the values gotten from the user. This
way, the arguments passed in the function call are lost.</p>
<p>So how can we correct this? One way is creating a function that
receives three parameters, as the student already did. But our
function will just iterate and print out the results:</p>
<pre class="programlisting">
void count_up(int start, int end, int step) {
  int x;
  for(x = start; x &lt;= end; x += step) {
    printf(&quot;%d\n&quot;, x);
  }
}
</pre>
<p>That was easy. Now comes the tough part. We have to read the
input from the user, and <span class="bold"><b>make sure it makes
sense</b></span>. Note that <tt class="function">count_up()</tt>
doesn't make any validity checking. It relies on external code for
this (of course this is a personal choice). This is one possible
way to get a value from the standard input:</p>
<pre class="programlisting">
printf(&quot;Enter the lower limit: &quot;);
fflush(stdout);
if(scanf(&quot;%d&quot;, &amp;start) &lt; 1)
  return EXIT_FAILURE;
</pre>
<p>Some things to note: first of all, because of buffering, we
should make sure the message is flushed for the user to see it.
This is the reason the explicit call to <tt class=
"function">fflush()</tt> is made. Also note that the return value
of <tt class="function">scanf()</tt> is checked against invalid
input. As we're reading just one value at a time, we check for
exactly one value read correctly. In case of failure, why do we
return instead of asking the user for another try? One of the
problems with <tt class="function">scanf()</tt> is that it is not a
simple task to know the status of the stream in case of failure
[3].</p>
<p>At last, we should check the step size is a positive number,
otherwise, we'd get strange results (e.g. infinite loops in case of
zero, etc.)</p>
<p>I also check that the lower limit is at most equal to the upper
limit (anyway, if this checking were not present, the loop wouldn't
execute)</p>
<p>So how would our program look like?</p>
<pre class="programlisting">
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

/* Step up and print within the given limits
 * Makes no validity checking              */
void count_up(int start, int end, int step) {
  int x;
  for(x = start; x &lt;= end; x += step) {
    printf(&quot;%d\n&quot;, x);
  }
}

int main(void) {
  int lower, upper, step_size;
/* Now we'll try to get the three values 
 * needed In case of error the program 
 * terminates  */
  printf(&quot;Enter lower limit: &quot;);
  fflush(stdout);
  if (scanf(&quot;%d&quot;, &amp;lower) &lt; 1) 
    return EXIT_FAILURE;
  printf(&quot;Enter upper limit: &quot;);
  fflush(stdout);
  if (scanf(&quot;%d&quot;, &amp;upper) &lt; 1) 
    return EXIT_FAILURE;
  printf(&quot;Enter step size: &quot;);
  fflush(stdout);
  if(scanf(&quot;%d&quot;, &amp;step_size) &lt; 1) 
    return EXIT_FAILURE;

/* Before calling count_up(), we have to
 * make sure the values are valid */
  if(lower &gt; upper) {
    fprintf(stderr, &quot;Invalid limits\n&quot;);
    return EXIT_FAILURE;
  }

  if(step_size &lt;= 0) {
    fprintf(stderr, 
        &quot;Invalid step size: %d\n&quot;, step_size);
    return EXIT_FAILURE;
  }
  count_up(lower, upper, step_size);
  return 0;
}
</pre>
<p><span class="bold"><b>End notes:</b></span></p>
<p>[0] See subclause 6.7.5.3 of the ISO-IEC 9899:1999 for more
details.</p>
<p>[1] See subclause 6.9.1 of the ISO-IEC 9899:1999 for more
details.</p>
<p>[2] See subclause 7.19.6.4 of the ISO-IEC 9899:1999 for more
details.</p>
<p>[3] It is generally recommended to use fgets() and strtol() in
these cases.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e164" id="d0e164"></a>From: Stuart
Golodetz <tt class="email">&lt;<a href=
"mailto:sgolodetz@dial.pipex.com">sgolodetz@dial.pipex.com</a>&gt;</tt></h3>
</div>
<p>Dear Student,</p>
<p>There are a number of issues with your code that need attention,
so rather than writing a lengthy introduction, I'll launch straight
in and try and explain the problems. The most urgent problems are
syntax errors, since these will stop your program compiling: until
you fix them, you can't even use your debugger to see where you're
going wrong, since you can't even build the program, let alone run
it.</p>
<p>The first problem to note is that you have missed a closing
brace at the end of your main function. Since the function body
must be enclosed in braces, omitting the ending brace will cause
problems, due to the fact that the compiler thinks everything up to
the closing brace is part of the function definition. In this case,
it will reach the end of the file without finding a closing brace,
which will cause it to choke.</p>
<p>The next problems we need to look at are in the <tt class=
"function">count_up</tt> function. Your calls to the scanf function
are rather haphazard and seem to indicate that this is something
that you have been taught, but have forgotten. The <tt class=
"function">scanf</tt> function is declared as follows:</p>
<pre class="programlisting">
int scanf(const char *format, ...);
</pre>
<p>It takes a variable number of arguments, but the first argument
tells it how many to expect. Because it needs to read into the
variables you specify, you must pass pointers to the variables
rather than the variables themselves (unlike C++, C does not have
references). This is because parameters are passed by value,
meaning that a local copy of them is made on the stack, hence if
the scanf function took variables as its parameters rather than
pointers to them, it would be modifying local copies rather than
the variables themselves. Looking at the code you've written,
several points can immediately be made:</p>
<pre class="programlisting">
scanf(%d; &amp;start)
</pre>
<div class="orderedlist">
<ol type="1">
<li>
<p>The first parameter is of type <tt class="type">const char
*</tt>. The usual method of passing a format parameter is by using
a string literal, which needs to be enclosed in speech marks. Hence
you need to write &quot;<tt class="literal">%d</tt>&quot; rather than simply
<tt class="literal">%d</tt>.</p>
</li>
<li>
<p>When calling a function, you must separate arguments to it with
a comma, not a semi-colon. If you use a semi-colon, the compiler
thinks it's the end of the statement and spits out an error. The
most likely reason behind this is that you were trying out an
example from a book and misread the character (as the visual
difference between , and ; in some fonts is negligible). If this is
the case, then I can only recommend you look more carefully at the
code. Accuracy is absolutely vital when programming.</p>
</li>
<li>
<p>You are missing a semi-colon at the end of the statement. This
is probably a simple typographical error, in which case the only
solution is to pay more attention when you're typing code.</p>
</li>
</ol>
</div>
<p>When all these corrections have been applied, the final version
of the statement is:</p>
<pre class="programlisting">
scanf(&quot;%d&quot;, &amp;start);
</pre>
<p>Your other scanf calls suffer from similar problems, but also an
additional one relating to the information about <tt class=
"function">scanf</tt> I presented above. There is a marked
difference (one works, the other causes undefined behaviour:
anything from a simple crash to evil demons descending on your
house and frying your computer - the standard doesn't specify)
between <tt class="literal">scanf(&quot;%d&quot;, &amp;end);</tt> and
<tt class="literal">scanf(&quot;%d&quot;, end);</tt>. The first one works as
intended, but the second one is a common example of how to crash
your program. The point is that if (for example), <i class=
"parameter"><tt>end</tt></i> contains 0, the function will merrily
go right ahead and try to dereference it, as if it were a pointer.
Needless to say, the results are undefined.</p>
<p>We're entering the home straight as regards syntax errors!
Examine the following (whilst bearing in mind that this does not
apply if you're using C99):</p>
<pre class="programlisting">
int x;
</pre>
<p>A simple declaration of an integer, you think. Unfortunately,
you seem to have forgotten the famous estate agent's mantra:
&quot;Location, location, location.&quot; In this case, remembering it would
have led you directly to the solution to your problem, namely that
it needs to go at the start of the scope.</p>
<p>The final syntax error can now be ironed out. In the line:</p>
<pre class="programlisting">
for(x=start; x&lt;=finish;x=x+step) {
</pre>
<p><tt class="varname">finish</tt> is an undeclared identifier.
It's fairly clear that you've made this error by forgetting that
you called your variable <tt class="varname">end</tt>. The best way
to avoid these errors in the future is to adopt a consistent naming
style so that you know, for example, that given a choice between
<tt class="varname">end</tt> and <tt class="varname">finish</tt>,
you always prefer the former. Whilst we're on this line, it's also
worth pointing out that it is generally better style to write
<tt class="literal">x=x+step;</tt> as <tt class=
"literal">x+=step;</tt>. With all these syntax errors mercifully
out of the way, the (now compilable) code looks like this:</p>
<pre class="programlisting">
void count_up(int start, int end, int step) {
  int x;
  printf(&quot;enter the upper limit&quot;);
  scanf(&quot;%d&quot;, &amp;start);
  printf(&quot;enter your lower limit&quot;);
  scanf(&quot;%d&quot;, &amp;end);
  printf(&quot;enter step size&quot;);
  scanf(&quot;%d&quot;, &amp;step);
  for(x=start; x&lt;=end; x+=step) {
    printf(&quot;\n %d&quot;,x);
  }
}
int main() {
  count_up(1, 10, 1);
  count_up(-10, 10, 2);
  return 0;
}
</pre>
<p>Now would be a good time to rejoice, were it not for the fact
that the code still doesn't work as originally intended. To
understand why this is so, examine the function calls in <tt class=
"function">main</tt>. You are passing parameters to the function,
yet they are not being used! Clearly this is less than cunning
(something technically known as a logic error).</p>
<p>The solution, as it turns out, is fairly simple and has the
handy sideeffect of fixing the logic error of incorrect prompting
(unless <tt class="literal">step &lt; 0</tt>, <tt class=
"varname">start</tt> is the lower limit, not the upper limit). The
solution is, in fact, to simply delete the prompt code. After all,
we have already passed the two limits and the step value into the
function; we don't need to query a poor, overworked user for them!
The revised code now looks as follows:</p>
<pre class="programlisting">
void count_up(int start, int end, int step) {
  int x;
  for(x=start; x&lt;=end; x+=step) {
    printf(&quot;\n %d&quot;,x);
  }
}
</pre>
<p>This is pretty close to what we want, as well as being much
simpler than the original. However, there are a couple more
problems we need to fix. First of all, consider the following
call:</p>
<pre class="programlisting">
count_up(1,10,0);
</pre>
<p>This seemingly innocuous call will put our function into an
infinite loop. (Or as one wise programmer once put it: &quot;Oops!&quot;)
There are two possible solutions to this:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>We can define a sensible behaviour for our function if step is
0. Perhaps it could output the start value once and then return.
Perhaps it could just return without outputting a thing. However,
we need to consider whether it actually makes sense to pass a step
value of 0. Rapidly coming to the conclusion that it doesn't, we
proceed to:</p>
</li>
<li>
<p>Abnormally terminate the program if <tt class=
"varname">step</tt> is 0. The easiest way to do this is using the
old workhorse, <tt class="function">assert</tt>:</p>
<pre class="programlisting">
#include &lt;assert.h&gt;
void count_up(int start, int end, int step){
  int x;
  assert(step!=0);
  for(x=start; x&lt;=end; x+=step){
    printf(&quot;\n %d&quot;,x);
  }
}
</pre></li>
</ol>
</div>
<p>The function is now both correct and safe. However, the name
<tt class="function">count_up</tt> is misleading, since the
function outputs the numbers. In fact, it is difficult to find a
sensible name for it, which suggests that perhaps it isn't an
altogether sensible function at all. It would probably be better to
simply write the function body (which is essentially just a for
loop) into the calling function, especially since C89 does not
support <tt class="literal">inline</tt>. A further point is that
the output might look better if you had written <tt class=
"literal">printf(&quot;%d\n&quot;,x);</tt>, although this is an aesthetic
point which may or may not be helpful.</p>
<p>Hope this helps,</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e306" id="d0e306"></a>From the
Harpist</h3>
</div>
<p>I wonder what Francis is after. There are quite a few syntax
errors scattered through the code. And I suspect that one of those
(the lost closing brace of main) was an artifact of the process of
laying out the material for printing (<i><span class="remark">It
was. Francis</span></i>). However one thing sits up and shouts at
me, the curious case of a function that ignores its arguments and
promptly asks the user for new values. That is where I am going to
focus most of my attention. Syntax is easy to fix, but that mistake
suggests that the student does not yet understand what a function
is and how it works.</p>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e314" id="d0e314"></a>Names are
Vital</h4>
</div>
<p>Most programming languages are built round the idea that
programmers can invent new things and give them names. We need to
distinguish three fundamentally different places where names will
occur in a program. These are declaration, definition and use.</p>
<p>A declaration is when we introduce a name into our code. We use
names for lots of different things. The most important to start
with are names of functions and names of variables. Actually we
usually combine the declaration and definition of a variable and
write things like:</p>
<pre class="programlisting">
int start;
</pre>
<p>which both tells the computer that start is the name of some int
storage (the declaration) and instructs the compiler to provide
that storage (the definition). If we do not want to define (provide
storage) for a variable but just want to tell the compiler that you
will provide that storage elsewhere (i.e. we just want a
declaration) we have to write:</p>
<pre class="programlisting">
extern int start;
</pre>
<p>Do not worry about that now, because separation of declaration
and definition of variables is unusual in C until you get to things
like struct. But that is another story that we will leave for
another day.</p>
<p>Function names are rather different because as we get to writing
larger programs we want to be able to split them into many files
(which can be reused in other programs). More than that, we want to
separate uses of functions from definitions. A function can only be
defined once (well think about it, how would you cope with two
definitions, if they were different you would have a mess, and if
they were the same you are wasting time writing them twice.) It can
be used many times - that is a basic reason for writing functions.
Everywhere it is used the compiler needs to know what we are
talking about even though it only needs to know how to do it once.
The former is what we call a declaration. For historical reasons
there are two types of function definition in C, the original one,
often called a K&amp;R style function definition and the newer (and
safer one) that is called a prototype. Most of us only use
prototypes these days and so I am not going to say anything about
the other form here.</p>
<p>A prototype has 3 parts. The first part is a type (<tt class=
"type">int</tt>, <tt class="type">double</tt>, <tt class=
"type">char*</tt> etc.) that tells the compiler what kind of result
it is going to get when the function is used (called). The second
part is the name that identifies the function. The third part is a
comma-separated list of types that is placed in parentheses. That
third part tells the compiler what information the function will
expect to be included when the function is used. That last part is
called a parameter list. We can, but we do not have to, add a name
after each type in the parameter list. The compiler does not care,
but those names can help the programmer understand what information
is needed when the function is used (called).</p>
<p>A pure declaration ends with a semi-colon. If we end it with an
opening brace it becomes a definition. Actually it is impossible to
write a definition that is not also a declaration. You cannot tell
a compiler how to do something without at the same time telling it
what you are doing. So now let me relate this to your code:</p>
<p>Inside your <tt class="function">main</tt> you use <tt class=
"function">count_up</tt> twice. Assuming that the user understands
what the name of the function means s/he would expect the program
to output something like:</p>
<pre class="screen">
1 2 3 4 5 6 7 8 9 10
-10 -8 -6 -4 -2 0 2 4 6 8 10
</pre>
<p>and is likely to be more than a little surprised to receive:</p>
<pre class="screen">
Enter upper limit:
</pre>
<p>Even more surprising is that when s/he responds to the three
questions with 10, 1, 1 the program exits without any further
output. Well that assumes the syntax errors and use of an
undeclared variable are corrected. Now let me give you a reworked
version:</p>
<pre class="programlisting">
#include&lt;stdio.h&gt;
</pre>
<p>Note that <tt class="filename">stdio.h</tt> is largely made up
of declarations of things that are provided by a library file that
will have been compiled from the definitions of those
declarations.</p>
<pre class="programlisting">
void count_up(int start, int end, int step);
</pre>
<p>That is a prototype (function declaration) that tells the
compiler that <tt class="function">count_up</tt> when used will
need to provide values for three <tt class="type">int</tt>s. It
tells the programmer that these three <tt class="type">int</tt>s
will be used as a start, end and step size. The declaration also
states that there will be no usable return value (the effect of
having a <tt class="type">void</tt> return type).</p>
<pre class="programlisting">
int main() {
  count_up(1, 10, 1);
</pre>
<p>And the compiler can prepare code that will connect those three
values with space it assumes the definition of <tt class=
"function">count_up</tt> will provide. The job of making the
connection is done by something called a linker (it links uses with
definitions, hence the name).</p>
<pre class="programlisting">
  count_up(-10, 10, 2);
  return 0;
}
</pre>
<p>Now either here or in some other file that we compile and give
to the linker we must define <tt class="function">count_up()</tt>.
Here is a reasonable implementation:</p>
<pre class="programlisting">
#include&lt;stdio.h&gt; 
void count_up(int start, int end, int step) {
  int i;
  if(step &lt;= 0) {
    puts(&quot;zero step size, output suppressed&quot;);
  }
  else {
    for(i=start; i&lt;=end;i += step) {
      printf(&quot;\n %d&quot;,i);
    }
  }
}
</pre>
<p>Note how I handle inappropriate values for <i class=
"parameter"><tt>step</tt></i>. Later I would want to modify that
strategy, but for now that seems the best answer. Trap bad values,
issue a message and then ignore them. I do not bother to trap
<tt class="literal">start&gt;end</tt> because that simply does
nothing anyway.</p>
<p>Now, I can hear muttering about why separate the declaration
from the definition. The simple answer is that I can easily change
my mind about the definition, indeed I can have several different
definitions in different files and make my choice when I come to
link the code together. Of course there are other reasons for
separating out function definitions from declarations but you will
learn those from experience.</p>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e409" id="d0e409"></a>Student Code
Critique 15: Late Submission</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e412" id="d0e412"></a>From Brett
Fishburne <tt class="email">&lt;<a href=
"mailto:william.fishburne@verizon.net">william.fishburne@verizon.net</a>&gt;</tt></h3>
</div>
<p>Let me say, first, that on all the systems to which I had access
the code compiled and ran flawlessly. This puts me at a dramatic
disadvantage.</p>
<p>Unfortunately, lint also failed to find any problems that could
cause the segmentation fault on any of these systems.</p>
<p>Thus, my analysis may be completely wrong as I cannot test a
&quot;corrected&quot; solution and get different results. Given that, please
bear with me and do not laugh too hard if I am all wrong.</p>
<p>My first line of thought was to address what the meaning of the
&quot;segmentation fault&quot; could be. A segmentation fault is almost
always associated with improper use of a pointer. In my case, it is
almost always an inadvertently uninitialized pointer.</p>
<p>Since <tt class="literal">tmp=*a</tt> did not cause an error, it
seems that the bad pointer must be &quot;<tt class="varname">b</tt>.&quot; I
rigorously checked the logic of the reverse subroutine insuring
that &quot;<tt class="varname">b</tt>&quot; could never be out of bounds:</p>
<p>Minimum possible value of <tt class="varname">b</tt>:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p><tt class="varname">b</tt> is smallest when <tt class=
"varname">i</tt> is largest, since <tt class="varname">b</tt> is
reduced in size by <tt class="varname">i</tt>.</p>
</li>
<li>
<p><tt class="varname">i</tt> is largest when <tt class="literal">i
= (strlen(str)/2)-1</tt>.</p>
</li>
<li>
<p>by 2. the minimum of <tt class="literal">b = str[strlen(str) -
((strlen(str)/2) - 1) - 1] = str[strlen(str) -
(strlen(str)/2)]</tt></p>
</li>
<li>
<p>Since the <tt class="literal">strlen(str)/2</tt> is always less
than <tt class="literal">strlen(str)</tt> for any <tt class=
"literal">strlen &gt; 1</tt>, the minimum value of <tt class=
"varname">b</tt> is always within the string.</p>
</li>
</ol>
</div>
<p>Maximum possible value of <tt class="varname">b</tt>:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p><tt class="varname">b</tt> is largest when <tt class=
"varname">i</tt> is smallest, since <tt class="varname">b</tt> is
reduced in size by <tt class="varname">i</tt>.</p>
</li>
<li>
<p><tt class="varname">i</tt> is smallest when <tt class=
"literal">i=0</tt>.</p>
</li>
<li>
<p>therefore, the largest value of <tt class="literal">b =
str[strlen(str)-1]</tt> which is the last character of the
string.</p>
</li>
<li>
<p>Since <tt class="varname">b</tt> cannot exceed the length of a
string for any <tt class="literal">strlen &gt; 1</tt>, the maximum
value of <tt class="varname">b</tt> is always within the
string.</p>
</li>
</ol>
</div>
<p>Indeed, <tt class="varname">b</tt> is never out of bounds. That
doesn't mean, however, that <tt class="function">swap</tt> could
not be passed NULL pointers, so my next thought was that <tt class=
"function">swap</tt> should check for NULL pointers simply for
completeness. It is clear from the analysis, however, that, as
written, <tt class="function">swap</tt> will not be called with
NULL pointers and the problem is not that <tt class=
"varname">b</tt> has been assigned a NULL or rogue value.
<tt class="varname">b</tt> is always within the range of <tt class=
"varname">str</tt>.</p>
<p>This had me stumped for several days. Finally it occurred to me
that I was looking in the wrong place. If <tt class=
"varname">str</tt> was out of range, then <tt class=
"varname">b</tt> would be out of range! Of course, then, so, too,
would a and we know from the error message that a was not out of
range (otherwise the assignment to <tt class="varname">tmp</tt>
should have caused a segmentation fault. Of course, there is the
possibility that a just happened to point to a valid value, but
that kind of &quot;luck&quot; doesn't go well with such a structured code
critique. This did point out to me, however, that <tt class=
"function">reverse</tt> should also check for a NULL string.</p>
<p>Again I was stumped for several days. At long last the
breakthrough came. &quot;cheese&quot; is a string literal! How is this
important? Well, for those of you who have the ANSI C standard
handy, flip to 6.1.4 which tells you that string literals should
NOT be modified. When a string literal is modified, the behaviour
is &quot;undefined&quot; and that means that it should not be done. This is
the explanation for why some compilers don't have a problem with
this code. The &quot;undefined&quot; behaviour is to allow this particular
modification. In real life, however, a string literal should be
treated as &quot;<tt class="type">const char *</tt>&quot; not &quot;<tt class=
"type">char *</tt>&quot;.</p>
<p>It seems only fair that in the case of this student's code, the
student should have received a compiler error that warned of this
(<i><span class="remark">hang about, how could the compiler do
that? It needs to do quite a bit of analysis to spot the problem.
If reverse and swap were in different files the problem gets real
nasty real quick. - Francis</span></i>), not just a run-time error.
Fairness, however, is rarely the order of the day. Now we know the
cause of the segmentation fault and how to resolve it (don't use a
string literal!) The question, however, is whether there is a way
to prevent someone from calling <tt class="function">reverse</tt>
with a string literal. The answer is no.</p>
<p>Since the assignment is to <tt class="function">reverse</tt> the
string &quot;in place&quot; it doesn't make sense to rewrite <tt class=
"function">reverse</tt> so that it passes back a reversed string. A
hefty comment would be nice, but that is about the best that can be
done in this regard.</p>
<p>Let us now address the structure of the program itself, having
resolved the &quot;dirty little error&quot; and with resolution in hand. The
first, and most obvious error, is a failure to include <tt class=
"filename">&lt;stdio.h&gt;</tt>. Since <tt class=
"function">printf</tt> is used, this inclusion is appropriate, thus
the headers should be:</p>
<pre class="programlisting">
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
</pre>
<p>I, personally, hate the concept of &quot;side-effects.&quot; swap is
nothing but one big &quot;side-effect.&quot; On the other hand, swap does
exactly what you would expect it to do, so the &quot;side-effect&quot; isn't
so bad. I still prefer for a subroutine to return an error when an
error is possible, so I would rewrite swap to account for NULL
pointers as follows:</p>
<pre class="programlisting">
/* Swaps a and b returning 0 when successful.
 * Does nothing and returns -1 or -2 if a or b 
 * is a NULL pointer,respectfully */

int swap(char *a, char *b) {
  char tmp;
  if(a == (char *)NULL) return(-1);
  if(b == (char *)NULL) return(-2);
  tmp = *a;
  *a = *b;
  *b = tmp;
  return(0);
}
</pre>
<p>Along the same lines, <tt class="function">reverse</tt> is
similar to <tt class="function">swap</tt>. I would, thus, make
similar changes:</p>
<pre class="programlisting">
/* Reverses a string in place - don't call
 * with a string literal! Returns 0 when
 * successful, -1 when called with a NULL
 * pointer, and positive on a print error */
int reverse(char *str) {
  char *a, *b;
  int i, err=0;
  if(str == (char *)NULL) return(-1);
  for(i=0; i &lt; strlen(str)/2; ++i) {
    a = &amp;(str[i]);
    b = &amp;(str[strlen(str)-i-1]);
    (void)printf(&quot;swapping %c &amp; %c\n&quot;,
                 *a, *b);
    if(err=swap(a,b)) {
      if(err == -1) {
        (void)fprintf(stderr,
            &quot;The first character is NULL\n&quot;); 
      }
      else {
        (void)fprintf(stderr, 
            &quot;The second character is NULL\n&quot;);
      }
      return(-1);
    }
  }
  return(printf(
      &quot;The reversed string is: %s\n&quot;, str));
}
</pre>
<p>The <tt class="function">main</tt> program must be declared as
type <tt class="type">int</tt> according to the most recent
standards, so that should be added, the string literal needs to be
fixed, and a value returned:</p>
<pre class="programlisting">
/* Creates a string and then reverses it in 
 * place. Returns 0 on success, negative on a 
 * NULL pointer error, and positive on a 
 * printing error */
int main() {
  char notliteral[7];
  (void)strncpy(notliteral, &quot;cheese&quot;, 6);
  notliteral[6] = '\0';
  return(reverse((char *)notliteral));
}
</pre>
<p>[<i><span class="remark">Well I would have
written:</span></i></p>
<pre class="programlisting c3">
<span class="remark">char notliteral[] = &quot;cheese&quot;</span>
</pre>
<p><i><span class="remark">instead of those three lines.
Francis</span></i>]</p>
<p>The return value from <tt class="function">strncpy</tt> is
ignored because it is a pointer to <tt class=
"varname">notliteral</tt>. On the other hand, it is always a good
idea to be sure that any string is properly terminated, so the last
possible character of notliteral gets a NULL (<i><span class=
"remark">I disagree, you should know what your common tools do -
Francis</span></i>). In this case, the NULL character is necessary,
because <tt class="function">strncpy</tt> would only copy up to the
6th character (which did not include the implied NULL character on
the string literal). [<i><span class="remark">But it would have
copied the null terminator had you used seven instead of six. I
think the mechanism you used is far too error prone, being packed
with magic numbers. Francis</span></i>]</p>
<p>I ignore the return codes from <tt class="function">printf</tt>
and <tt class="function">fprintf</tt> (hence the <tt class=
"type">void</tt> cast) most of the time because there is nothing I
can do if those commands fail in this case. I can't warn the user
(printing already failed) and the whole function of the program is
to print the reversed string. If that fails, then the main program
sends the error on to the user as its return code.</p>
<p>[<i><span class="remark">void casts are not often used these
days because they actually add nothing other than tell maintenance
programmers that you know you ignored the return value. But how
often is ignoring a return value an error? And, by the way, note
that the entire printf and scanf family of functions are ones where
the side-effects are what we want. - Francis</span></i>]</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e670" id="d0e670"></a>Student Code
Critique 17</h2>
</div>
<p>It is time for a little C++ teaser. Identifying the problem
should not be too hard but I want rather more than that. I want
suggestions on coding idioms that will make the student's life
easier. And I will give you a big clue, making a function template
a friend of a class template is not a brilliant idea. Remember that
all elements of code are up for criticism. Critiques by September
16 to: <tt class="email">&lt;<a href=
"mailto:francis.glassborow@ntlworld.com">francis.glassborow@ntlworld.com</a>&gt;</tt>
please.</p>
<p>What's wrong with the program below?</p>
<pre class="programlisting">
template &lt;int N&gt;
class T {
  public: friend T operator+ (const T&amp;,
                              const T&amp;);
  private data[N + 1];
};
template &lt;int N&gt;
T&lt;N&gt; operator+ (const T&lt;N&gt;&amp; S1,
                const T&lt;N&gt;&amp; S2) {
  return S1;
}
int main() {
  T&lt;64&gt; a, b, c = a + b;
}
</pre>
<p>I can compile it, but I can't link it- the operator isn't
found.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e684" id="d0e684"></a>The Winner of
SCC 16</h2>
</div>
<p>The editor's choice is: David Caabeiro. Congratulations David!
Please email Francis to arrange for your prize.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
