CS551 - Self-Study Exercises
Coding Guidelines to Ensure Portability
The following guidelines have been developed through a process of trial-and-error with a wide range of C compilers,
In many cases, it should be obvious why these practices help guarantee that your application will be portable. Feel
free to consult the course instructor if you do not understand the intent or the rationale of a guidelines.
- Follow the conventions for file extensions (.c, .h, etc.);
conventions for X files will be covered in the exercises and assignments.
- Use meaningful identifier names -- no single characters except as loop counters.
- Follow C naming conventions: lower-case or mixed-case for ordinary identifiers; all caps for macro names
- Follow X naming conventions (provided on a reference sheet) for variables,
widget classes, resource names, callback routines, and all other X-specific
- Use numeric escapes only when no printable form or character escape is available.
- Use the conditional operator only where an if construct is not allowed.
- Use the comma operator only where a compound statement is not allowed.
- Use the sizeof operator (or a macro) rather than hard-coding size dependent information.
- Avoid pointer conversions whenever possible; when they are required, always use explicit type casts. Note
that many arguments to callback and similar functions are cast by Xt or Xlib to be "typeless pointers" (declared as
XtPointer or caddr_t), and therefore must be re-cast to the correct type before the data can be used.
- Use explicit parentheses to indicate the order of evaluation in pointer expressions.
- Use explicit typecasting, rather than relying on implicit rules for coercion.
- Use goto only when a multi-level or long-distance jump is needed.
- Terminate every case action with a break statement; if you
really intend for execution to continue through the next case action, state
that explicitly in a comment.
- Write all error messages to stderr, not stdout.
- Use calloc() (pre-initiliazes storage) and cfree(), rather than
malloc() and free().
- Explicitly declare all external and forward-referenced functions, int or not; this includes
- Explicitly specify the return type of every function.
- In any routine which must interface with Xlib or Xt, include the correct number and types of parameters,
regardless of whether or not they will actually be used.
- Explicitly control the scope of all data objects. Use static to hide data that does not
absolutely have to be shared, limiting its scope to just one module or function.
- Parenthesize macro definitions to avoid expansion errors.
- Explicitly initialize every pointer to NULL.
- Free all dynamic storage if it is only needed during part of the program.
This also applies to X resources (widgets, pixmaps, etc.).
- Explicitly nullify any pointer whose storage has been freed.