Write in parts
Finding one bug in the 20 lines you typed for the last fifteen minutes is easier
than finding fifty bugs in the two thousands lines you have typed for one month.
Good identifiers
Use long identifiers such as sum_of_the_weights instead of short ones. Use
longer identifiers for variables and functions used in many parts of the program.
If a variable is used only in a 5 line loop, it can be called s with no risk. If you
are really lazy, at least use acronyms (ws for weight sum for instance).
Also, reuse the same names and parameter order everywhere. Avoid at all cost
this sort of mess
int rectangle_surface(int xmin, int ymin,
int xmax, int ymax) {
return (xmax - xmin) * (ymax - ymin);
}
int rectangle_diagonal_length(int xmin, int xmax,
int ymin, int ymax) {
return sqrt(double( (xmax - xmin) * (xmax - xmin)
+ (ymax - ymin) * (ymax - ymin) ) );
}
Use constants instead of numerical values
It is extremely dangerous to have a consistency between values which is not made explicit. For instance, the size of an array which appears both for the allocation and in a loop should always be specified by the mean of a constant with a name. That way, it can be changed without having to change it in many places, and it also reminds you the semantic of that value (i.e. it is a number of elements).
Comment your code
Comments help the one who is going to use the source code later. It can
be somebody else, or it can be you in one month, or you in fifteen minutes.
Depending upon your goal – are you going to work in team ? who are you going
to work with ? are you planning to maintain this code ? will severe teachers
read it ? – your comments have to be more or less precise.
Always put comments if a piece of code has a non-obvious behavior, for instance
if there is a constraint on the parameters of a function, or if it returns values in
a strange way.
// Angle in degrees, radius in meter, returns square meters
double piece_of_pie_surface(double angle, double radius) {
return M_PI * radius * radius * angle / 180.0;
}
Symmetry and indentation
Arrange your source so that obvious missing or incorrect elements will be instantaneously spotted. Which of the two sources below is easier to debug
int size; cin >> size; double *a[size];
if(size > 0)
{
for(int i = 0; i < size; i++) {
a[i] = new double[i];
for(int j = 0; j < i; j++) a[i][j] = j + i;}
delete a[i];
}
int size;
cin >> size;
double *a[size];
if(size > 0) {
for(int i = 0; i < size; i++) {
a[i] = new double[i];
for(int j = 0; j < i; j++) a[i][j] = j + i;
}
delete a[i];
}
Note that in a given block of instructions, the number of new is equal to the
number of delete, except in rare cases. The example above does not respect
this rule.
More to read :- Use a DEBUG flag