C style

Ian Cottam ian at mucs.UX.CS.MAN.AC.UK
Thu Feb 18 03:35:41 AEST 1988


I would like to update the style list (below) that I give to students.
Any comments welcome.  Flames to /dev/null pls.
Email is best -- I will summerise.
ian at ux.cs.man.ac.uk
___________________

		Good C Style
		============

Note:  Advice that I, and a few others, have given but has been universely
       ignored is indicated by a + rather than a * in the list below!


* choose a personal or project standard for layout and stick to it

+ show the difference between = and == by using asymmetric layout
  for = (e.g. ptr= NULL;)

* use  expr == var  to emphasise and catch some = for == mistakes
  (e.g. x*2 == y)

+ avoid EXCESSIVE use of multiple exits from a context

* do not rely on defaults, e.g. extern/static variables being set to 0

* use void when you are writing a non-value returning function
  (not the default int)

* cast the return values of functions to void if you are certain that
  their result is not needed (have a list of exceptions to this rule
  e.g. printf, free)

* use lint as a matter of course (not just after 10 hours debugging)

* write portable C (Kernel level code, e.g. drivers, excepting.  Put
  all such code in a separate file.)

* use standard I/O (i.e. don't use UNIX specific I/O without good reason)

* don't use a macro if a function call is acceptably efficient

* avoid complex macros

* don't use complex conditional expressions especially ones returning
  non-arithmetic values

+ don't use assignment inside a complex expression
  (e.g. use (chptr= malloc(N), chptr != NULL)
        rather than
            ((chptr = malloc(N)) != NULL)

+ avoid #ifdefs for version control purposes (use a proper version
  control system)

* use typedef to build up (complex) declarations piecemeal

* use enumerations and #define for constant names
  (enum is preferable to #define, especially with ANSI C)

* always check the error status of a system call

* use header files, e.g. <stdio.h>, rather than assume, e.g., -1 == EOF

* try to avoid assuming the world uses ASCII (difficult one this!)

* use casts rather than rely on representational coincidences

* only have one copy of global declarations in a .h file

* do not embed absolute pathnames in program code (at least #define them)

+ use side-effect operations in statement context only
  (exception: the comma operator)

* use static for variables and functions that are local to a file

* use the ``UNIX standard'' for command line argument syntax

* split programs over several files for ``information hiding''

* never fall through the case arm of a switch statement

+ use local blocks to indicate the extent of variables and comments, e.g.
	{ /* this does foo */
		int foovar;
		/* stuff for foo */
	}
	{ /* this does bar */
		...etc...
	}

* don't use the preprocessor to make C look like anything but C



More information about the Comp.lang.c mailing list