From suckless.org/coding_style. The most important aspect of style is consistency.
main_POSIX_C_SOURCE 200809L._XOPEN_SOURCE 700./* */ for comments, not //.__VA_ARGS__ not a named parameter.{ on same line preceded by single space (except functions).} on own line unless continuing statement (if else, do while, ...).Use block for single statement if inner statement needs a block.
for (;;) {
if (foo) {
bar;
baz;
}
}
Use block if another branch of the same statement needs a block:
if (foo) {
bar;
} else {
baz;
qux;
}
Use tabs for indentation and spaces for alignment. This ensures everything will line up independent of tab size. This means:
#define began.grep ^functionname(.{ on own line (function definitions are a special case
of blocks as they cannot be nested).static.Example:
static void
usage(void)
{
eprintf("usage: %s [file ...]\n", argv0);
}
static.* is adjacent to variable name,
not type.if, for, while, switch (they are not
function calls).( and before the closing ).() with sizeof.sizeof().Example:
switch (value) {
case 0: /* FALLTHROUGH */
case 1:
case 2:
break;
default:
break;
}
type_t naming (it is reserved for POSIX and less
readable).CamelCase for typedef'd types.Do not use C99 bool types (stick to integer types).
Otherwise use compound assignment and tests unless the line grows too long:
if (!(p = malloc(sizeof(*p)))) hcf();
When functions return -1 for error test against 0 not -1:
if (func() < 0) hcf();
Use goto to unwind and cleanup when necessary instead of
multiple nested levels.
return or exit early on failures instead of multiple nested
levels.
Unreachable code should have a NOTREACHED comment.
Think long and hard on whether or not you should cleanup on fatal errors. For simple "one-shot" programs (not daemons) it can be OK to not free memory. It is advised to cleanup temporary files however.
Use enums for values that are grouped semantically and #define
otherwise:
#define MAXSZ 4096
#define MAGIC1 0xdeadbeef
enum {
DIRECTION_X,
DIRECTION_Y,
DIRECTION_Z
};