Style

Note that the following are guidelines and the most important aspect of style is consistency. Strive to keep your style consistent with the project on which you are working. It is up to the project maintainer to take some liberty in the style guidelines.

Recommended Reading

The following contain good information, some of which is repeated below, some of which is contradicted below.

File Layout

C Features

Blocks

Use block for single statement if inner statement needs a block.

for (;;) {
	if (foo) {
		bar;
		baz;
	}
}

Use another branch of the same statement needs a block:

if (foo) {
	bar;
} else {
	baz;
	qux;
}

Leading Whitespace

Use tabs for indentation and spaces for alignment. This ensures everything will line up independent of tab size. This means:

Functions

Example:

static void
usage(void)
{
	eprintf("usage: %s [file ...]\n", argv0);
}

Variables

Keywords

Switch

Example:

switch (value) {
case 0: /* FALLTHROUGH */
case 1:
case 2:
	break;
default:
	break;
}

Headers

User Defined Types

Line Length

Tests and Boolean Values

if (!(p = malloc(sizeof(*p))))
	hcf();

Handling Errors

if (func() < 0)
	hcf();

Enums and #define

Use enums for values that are grouped semantically and #define otherwise:

#define MAXSZ  4096
#define MAGIC1 0xdeadbeef
enum {
	DIRECTION_X,
	DIRECTION_Y,
	DIRECTION_Z
};