Table of Contents


APPENDIX A — C CODING SUGGESTIONS

Chapter 2

*  Don't use = in an if statement expression, unless it is absolutely necessary.
*  Define a macro EQ for ==, and never use ==.
*  Define macros for &, |, &&, and ||.
*  Define macros for BOOL, TRUE, and FALSE.
*  Use only Boolean-valued expressions in if statements.
*  Use only Boolean variables with the logical operators && and ||.
*  Do all assignments as separate statements, not as part of a more complex expression.
*  Use parentheses in expressions to explicitly define order of evaluation.
*  Don't use %i format specifications or numbers that begin with 0.
*  Be sure to code addresses for arguments to scanf and similar functions.

Chapter 3

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

Chapter 4

*  Declare C arrays with one extra element, and don't use the element with subscript 0.
*  Use macros to define tables and loops over them.
*  Always guard a string assignment against overwriting the target variable.
*  Create macros and functions to define strings and provide "safe" string operations.

Chapter 5

*  Declare functions static if you intend to call them only from within the same source file.
*  Use the most restricted visibility possible for variables; avoid shared variables.
*  Put all external declarations before the first function definition in a file.
*  Put functions that must share data and external declarations for their shared variables in a file by themselves.
*  Use EXPORT, SHARE, and IMPORT macros to clarifythe intended visibility of a variable.

Chapter 6

*  For non-array "output" or "input/output" parameters, use local variables instead of dereferenced parameters in function calculations.
*  Use array notation instead of pointers anddereferencing when you're working with arrays.
*  When working with pointers in assignment statements, double-check that you're using the right level of indirection.
*  Unless you're positive a pointer has been initialized, check it for NULL before using it.
*  Use a new_string function to return new strings from functions.
*  Always check for a NULL return value after calling malloc.
*  Use the allocate macro to prevent memory "leakage."
*  Always initialize pointers in their definitions.
*  Use typedef and PTR, contents_of, and address_of macros to improve program readability.
*  Avoid popular, but tricky, C idioms for business application programming.
*  Don't use ++ or — in assignments.


Table of Contents