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.

User-defined Symbols

  1. Follow the conventions for file extensions (.c, .h, etc.); conventions for X files will be covered in the exercises and assignments.
  2. Use meaningful identifier names -- no single characters except as loop counters.
  3. Follow C naming conventions: lower-case or mixed-case for ordinary identifiers; all caps for macro names and typedefs.
  4. Follow X naming conventions (provided on a reference sheet) for variables, widget classes, resource names, callback routines, and all other X-specific elements.
  5. Use numeric escapes only when no printable form or character escape is available.


  1. Use the conditional operator only where an if construct is not allowed.
  2. Use the comma operator only where a compound statement is not allowed.
  3. Use the sizeof operator (or a macro) rather than hard-coding size dependent information.
  4. 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.
  5. Use explicit parentheses to indicate the order of evaluation in pointer expressions.
  6. Use explicit typecasting, rather than relying on implicit rules for coercion.


  1. Use goto only when a multi-level or long-distance jump is needed.
  2. 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.
  3. Write all error messages to stderr, not stdout.
  4. Use calloc() (pre-initiliazes storage) and cfree(), rather than malloc() and free().


  1. Explicitly declare all external and forward-referenced functions, int or not; this includes calloc().
  2. Explicitly specify the return type of every function.
  3. 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.
  4. 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.
  5. Parenthesize macro definitions to avoid expansion errors.
  6. Explicitly initialize every pointer to NULL.
  7. Free all dynamic storage if it is only needed during part of the program. This also applies to X resources (widgets, pixmaps, etc.).
  8. Explicitly nullify any pointer whose storage has been freed.