* * * * *
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.