Why is C hard to understand?

Frank Glandorf gefrank at sdrc.UUCP
Thu Oct 4 07:31:18 AEST 1990




Answer: Same reasons as FORTRAN, Pascal, PL/1, etc.

While checking out some code the other day I came across a rather
obscure looking function and decided to restructure it to try to
understand it.  The function determines if a set of surfaces
forms a closed object. The number of lines was reduced from about
250 to 110.  The number of local variables was reduced from 49 to
33 (three of which are const).  The number of control flow
structures was reduced from 31 to 13. 

The first task was a superficial cleanup. This consists of a
uniform indentation style, elimination of curly braces from
single line control structures, replacing of lines of comment
stars with blank lines, replacing literal "magic values" with
symbolic names, and replacing multiple line statements with
single lines. 

The next method applied was to make use of procedural
abstraction. This eliminated eight for loops (note: there are
about four lines per loop). The following types of functions were
used: vector sum, vector difference, vector times a scalar,
vector copy, and cosine of angle between two vectors.

The largest simplifications result from a true understanding of
the function. In one case two nearly identical sequential while
loops were combined. The first loop is used to find a nondangling
surface and save some information about it. The second loop finds
a nondangling surface which is closer to some point than the
previous surface and saves the same information about it. The two
loops can be combined by adding a variable which tracks if a
previous surface has been saved. 

In another case the cosine of the angle between two vectors is
computed and a set of nested if-then-else statements are used to
set the open/closed object flag. The nine lines of inline cosine
computation were replaced with a function call.  Every other line
of this section had a comment describing the vector operations.
None of them stated the intent of this section which was to
determine if the angle between two vectors was acute. 

Three errors were uncovered by restructuring the code. The first
was a variable which had not been set correctly. Another error
resulted from returning an error code from a system which had no
meaning for this function. The last error failed to free
allocated memory when finished with it. 

To be fair, I doubt if this module had started out this complex.
There are half a dozen modifications listed. A large function
seems to grow more than a small one since during its maintenance
one is more likely to patch a large function and restructure a
small one. 

-Frank



More information about the Comp.lang.c mailing list