C Language

Real Programmers And C

The problems with C itself would be more manageable if the culture and practices that have grown up around C weren't also rooted in machine-level, systems programming. Consider something as simple as adding a new element to an array. Two favorite C idioms for this operation are:

 array[++top] = item;
 array[next++] = item;

The first example increments top, then adds item to array[top]. The second example adds item to array[next], then increments next. In C, arrays are really just synonyms for pointers; and this coding style follows an assembly language practice of combining an address increment with a memory reference to the address. But in a high-level language, there's no reason to code these operations in a single statement. (You might, of course, want to create a procedure, such as add_item(array, item) so that a single, meaningful statement can be used to add an item. But that's not the point here, since both the increment and assignment operations are coded explicitly in the example.)

The most important problem with this condensed coding style is that, when you're reading volumes of code, it's easy to overlook statements where the ++ increment has been placed on the wrong end of the index identifier. The following alternatives use the code's visual layout to show the critical sequence of operations:

 ++top;
 array[top] = item;
 array[next] = item;
 ++next;

These alternatives also eliminate the need to use post increment (and post decrement) operations, removing one more piece of syntactic clutter and a potential source of coding errors from the program. Note also that the two-statement alternatives are just as easy to write and, with most optimizing C compilers, will execute as fast as the one-statement approach.

To most people, even non-C programmers, the difference in clarity in these isolated one- or two-line examples is small. However, in large programs or more complex statements, the differences mount up. As the examples point out, conventional C style - much of it based on assembly language programming techniques - can also lead to subtle, but fatal, program errors.