A List Of Rules That Every C Programmer Should Follow
Here’s a list of rules that every C programmer should follow. Occasionally, a rule may be violated, but only for a really good
- Most standard functions have a header associated with them, which should always be included. The manuals often fail to identify what this header is, although it’s there in “/usr/include” (or wherever). You might consider grepping the header files to discover what headers go with what functions. This rule means that most C files will start with 5 to 10 includes. Don’t feel weird if some of your files start with even more.
- Never declare a function if it’s declared in a header, as redundant declarations lessen reliability, portability, and maintainability. If you discover that some standard functions aren’t in any header, you might consider coding a header so you can just include it all the time.
- Always declare the return value of a function when the function is defined, even if it’s “int”. This makes your intent clear. It also avoids letting a function default to “int” when it should have been declared “void”.
- For functions internal to a file (and, therefore, not declared in a header), order them so that redundant declarations aren’t necessary. That is, order them as a Pascal program would be, with “main” at the end. Only in the case of mutual recursion is this impossible.
- Always call “exit(0)” at the end of “main”.
- Make all variables and functions “static”, unless they are external to the file.This helps the reader by indicating thelocality of the object, and it also avoids name clashes in the linker.
- Don’t use “int”, “0”, and “1” for Boolean operations, as these are needlessly general. Instead, use these:
typedef int BOOLEAN;
#define FALSE 0
#define TRUE 1
- Where a logical expression is required (“if”, “while”, etc.), do not write an integer expression. That is, do this:
if (*p != ‘