Learning C // Part III

After doing another course in C programming there is a new lesson. There are some hints on programming and most of them apply to any language, not just C. The following rules are recommendations which are true in most cases (but not all). You might also be interested in reading part I and part II of this series.

  • If you indent more than 4 times (because of nested if/else/for/.. constructions) you should modularize. This is creating sub-functions which are called from within the function in question.
  • If a function has more than 10 local variables you should modularize.
  • If you intend to use a global variable you should rethink your solution.
  • If your function has more than 4 arguments you should modularize.
  • Prefer the stack over the heap. This is if it is possible to solve a problem by using local variables or local arrays then don’t malloc(). Malloc() only if you either need more than 100 kBytes of memory or you need dynamic memory which means you don’t know the amount of memory at the time of writing the program (i.e. you don’t know it before runtime).
  • Always manually check the corner cases of loops. Consider the following code snippet and find the bug:
/*! This function sorts an integer array.
 * @param a Pointer to the array.
 * @param acnt Number of elements of the array.
 */
void bubblesort(int *a, int acnt)
{
   for (int i = 0; i < acnt; i++)
      for (int j = i; j < acnt - i; j++)
         if (a[j] > a[j + 1])
            swap(&a[j], &a[j + 1]);
}

 

Comments are closed.