[prev] [up] [overview] [next]

Section 14. Style

14.1: Here's a neat trick:

	if(!strcmp(s1, s2))

Is this good style?

It is not particularly good style, although it is a popular idiom.  The test succeeds if the two strings are equal, but its form suggests that it tests for inequality.

Another solution is to use a macro:

	#define Streq(s1, s2) (strcmp((s1), (s2)) == 0)

Opinions on code style, like those on religion, can be debated endlessly.  Though good style is a worthy goal, and can usually be recognized, it cannot be codified.

14.2: What's the best style for code layout in C?

K&R, while providing the example most often copied, also supply a good excuse for avoiding it:

The position of braces is less important, although people hold passionate beliefs.  We have chosen one of several popular styles.  Pick a style that suits you, then use it consistently.
It is more important that the layout chosen be consistent (with itself, and with nearby or common code) than that it be "perfect."  If your coding environment (i.e. local custom or company policy) does not suggest a style, and you don't feel like inventing your own, just copy K&R (The tradeoffs between various indenting and brace placement options can be exhaustively and minutely examined, but don't warrant repetition here.  See also the Indian Hill Style Guide.)

The elusive quality of "good style" involves much more than mere code layout details; don't spend time on formatting to the exclusion of more substantive code quality issues.

References: K&R Sec. 1.2 p. 10.

14.3: Where can I get the "Indian Hill Style Guide" and other coding standards?

Various documents are available for anonymous ftp from:


[prev] [up] [overview] [next]