Good programs are readable by humans, not just readable by compilers. Programs are read and re-read during the development process, and useful programs are read by others who wish to extend, modify, and enhance them. Writing good programs, then, has much to do with writing programs that are easily understood by human readers.
For example:
/* average.c This program reads a list of numeric grades from standard input, and computes the count and average grade. Any grades not between 0.0 and 100.0 are rejected. Ray Ontko, 1999/10/05 */
You may wish to include other information in this documentation header as well. Instructions on how to run the program, a history of changes that have been made to the file, and notes about what is broken are sometimes included.
If your function or variable name contains several "words", separate the words using the underscore character, or perhaps capitalize the first letter of each word. Surely "final_total" or "FinalTotal" is easier to read than "finaltotal".
Be consistent in the degree to which you indent for each level of nesting in the control structure. By convention, C programmers indent in multiples of 2 or 4 spaces.
You should also make a choice and be consistent about whether you indent the "{" and "}" which define a block. For example:
main()
{
float grade ;
int count = 0 ;
float total = 0.0 ;
printf( "Enter grades, one per line, or CTRL-D to end.\n" ) ;
while ( scanf( "%f" , &grade ) == 1 )
{
if ( ( grade < 0.0 ) || ( grade > 100.0 ) )
{
printf( "Must be between 0 and 100; try again.\n" ) ;
continue ;
}
count ++ ;
total += grade ;
}
if ( count > 0 )
{
printf( "Count = %d\n" , count ) ;
printf( "Average = %.2f\n" , total / (float)count ) ;
}
}
In the example above, note that each "{" is vertically aligned with the matching "}" of the block, and that all statements within each block are indented equally, and that all indents are multiples of the smallest indent (in this case, 2).
printf("Average = %.2f\n",total/(float)count);
printf( "Average = %.2f\n" , total / (float)count ) ;
printf( "Average = %.2f\n" , total / ( float ) count ) ;
The three statements above all do the same thing, but
it might be argued that the first is too compressed, while the
last is too spread out. Reasonable people might disagree over
exactly which spaces should be inserted to achieve optimum
readability, but all would agree that spacing can help guide
the reader to notice what's important in the line.
As with horizontal spacing, be judicious in your use of vertical whitespace; some is good, but more isn't necessarily better. Use it to help your reader see the "paragraphs" in your code.
As with all writing, be sure to use correct spelling, punctuation and grammar. Programs are hard enough to read without having to account for illiterate programmers.
Copyright © 1999, Ray Ontko (rayo@ontko.com).