C Language

From C to Shining C

If C's pitfalls somewhat tarnish its image, remember that your C programs can still shine if you polish your programming techniques. The most important thing you can do to improve C programs is take "C-riously" the dangers of writing C code in the traditional (some would say, "C-eat of the pants") manner. Don't try to make your C code "do a lot with just a few statements," and don't hesitate to use source macros to lift yourself to a higher, safer language level than C primitives. Sure, your code will look foreign to old-style C programmers, but your running programs will look a lot better to your end users.

* * * * *

Answer to Chapter 2's puzzle: Figure 3.3 shows corrections to the three errors in the original code. The structure definition was missing the final semicolon (A), causing the compiler to treat the definition as the return type of the main function. The for loop had an extra semicolon immediately after the parentheses (B), so the body of the for loop was the null statement instead of the code within the braces. And the printf format string was missing (C) a newline character (\n), causing the results to be printed in a continuous stream, rather than one item per line.

Figure 3.3 - Corrected C from Chapter 2

 struct part  {
  int part_number;
  char description[30];
 };
 main() {
  int i;
  /* Array of part numbers and descriptions */
  struct part part_table[100] =
  {
    {011,  "Wrench"     },
    {067,  "Screwdriver" },
    {137,  "Hammer"      },
    {260,  "Pliers"  },
    /*etc. */
    {0,   "sentinel" }
  };
  for (i=0; i<100; i++) /* Print the list of parts */
  {
   if (part_table[i].part_number == 0)
     break;
   printf("%i  %s\n", part_table[i].part_number,
              part_table[i].description);
  }
 }

Sidebar 1 - C Coding Suggestions

* Always enclose conditional code in braces.
* Do all assignments as separate statements, not as part of a more complex expression.
* Use parentheses around expressions on return statements.
* Never use the C switch statement.
* Place the opening /* and closing */ for comments on lines by themselves, and use a | to begin each line of comment text.

by BrainBellupdated
Advertisement: