next up previous contents
Next: Modularity and Functions Up: C Programming for Research. Previous: C Programming for Research.   Contents

Indentation and Commenting

Writing understandable software starts with sensible use of indentation, but try not to use tab characters as they can take different sizes depending upon your editor. This may not cause an immediate problem for you, but it will for others.

Rather than treating the software as a piece of literature (where each variable or function name can easily become a sentence), it actually helps not to use un-necessarily long variable or function names. Preferably, common variables within functions should take common names which other programmers may conventionally use for the same task. Otherwise, others reading your software will need to keep refering to the top of the file or function to remember how variables were defined. It is quite appropriate to define locations in a 2D co-ordinate system as x or y and loop integers as i,j or k. There is no need to name them in a more complicated way which may be more meaningful to you, it's what others will see that is important and if people are to read your software and understand it keeping things simple helps with the flow. For a bad example of what not to do

 my_array_of_data[data_iterator] = my_other_array_of_data[data_iterator]
                                  +my_other_array_of_data[data_iterator+1];
as opposed to simply
a[i] = b[i] + b[i+1];

Contrary to common coding convention, for loops should be written as

for(i=0;i<num_int;i++) 
{
}
and NOT
for(i=0;i<num_int;i++) {
}
As the former makes code indentation easier to check, particularly when following loops over several pages in an editor.

Put comments in your software but do not overuse them. Complex functions probably need some comment on the definition of parameters and expected returned values. These should be placed immediately after the function definition. However, comments like

/* a for loop over i */
for(i=0;i<num_int;i++) 
{...}
and also
/* output the data */
   output_data();
are completely unnecessary. In general, comments which merely describe the meaning of existing C syntax should be avoided. A reasonably competent programmer will understand the software more quickly if he does not need to read around such comments.

Take the time to write the comments: when you feel they are unlikely to need changing; when you expect the software to soon be made availablee to others; or when you think you may not be developing the software for some time.

Don't use C++ style comment markers ``//'' unless they are expected to be temporary, as they do not compile properly on all platforms.


next up previous contents
Next: Modularity and Functions Up: C Programming for Research. Previous: C Programming for Research.   Contents
root 2017-09-20