Expert C Programming

(Jeff_L) #1

  • Yet a third white space problem occurred when a programmer had two pointers-to-int, and
    wanted to divide one int by the other. The code said



ratio = x/y;


but the compiler issued an error message complaining of syntax error. The problem was the

lack of space between the "/ " division operator and the "* " indirection operator. When put


next to each other they opened a comment, and hid all the code up to the next closing
comment!

Related to opening a comment without intending to, is the case of accidentally not closing a comment
when you did mean to. One release of an ANSI C compiler had an interesting bug. The symbol table
was accessed by a hash function that computed a likely place from which to start a serial search. The
computation was copiously commented, even describing the book the algorithm came from.
Unfortunately, the programmer omitted to close the comment! The entire hash initial value calculation
thus fell inside the continuing comment, resulting in the code shown below. Make sure you can
identify the problem and try to predict what happened.


int hashval=0;


/* PJW hash function from "Compilers: Principles, Techniques,


and Tools"


* by Aho, Sethi, and Ullman, Second Edition.


while (cp < bound)


{


unsigned long overflow;


hashval = ( hashval <<4)+*cp++;


if ((overflow = hashval & (((unsigned long) 0xF) << 28)) != 0)


hashval ^= overflow | (overflow >> 24);


}


hashval %= ST_HASHSIZE; / choose start bucket /


/* Look through each table, in turn, for the name. If we fail,


* save the string, enter the string's pointer, and return it.


*/


for (hp = &st_ihash; ; hp = hp->st_hnext) {


int probeval = hashval; / next probe value /


The entire calculation of the initial hash value was omitted, so the table was always searched serially
from the zeroth element! As a result, symbol table lookup (a very frequent operation in a compiler)
was much slower than it should have been. This was never found during testing because it only
affected the speed of a lookup, not the result. This is why some compilers complain if they notice an
opening comment in a comment string. The error was eventually found in the course of looking for a
different bug. Inserting the closing comment resulted in an immediate compilation speedup of 15%!


A Digression into C++ Comments


C++ doesn't address most of the flaws of C, but it could have avoided this inadvertent run-on


comment. As in BCPL, C++ comments are introduced by // and go to the end of a line.

Free download pdf