Jump to: navigation, search

These recommendations have been moved to Project:Policies#C_code. This page is reserved for a partial explanation of K&R formatting for those unfamiliar with it.

The basics of K&R formatting

  • whitespace:
    • a single space follows a keyword - if, while, etc - but not a function name
    • a single space follows and precedes all binary operators (with the exception of -> and . which should not be preceded or followed by whitespace) and each token of the ternary operator i.e.
      • x ? y : z rather than x?y:z
      • x += y rather than x+=y
      • somestr->somemember rather than somestr -> somemember
    • exceptions to the above are constructs like s[i+1] or x >> (p+1+n) which should not have spaces around the pluses
    • a single space follows a comma and follows each semicolon within a for loop's control statement.
    • a * when used as the dereference operator or as part of a pointer declaration, associates with the declared object/dereferenced expression i.e. char *p; rather than char* p;
  • braces:
    • for functions, the opening brace occurs at the start of a new line; likewise the closing brace
    • for all other blocks, the opening brace occurs at the end of the statement that opens the block, preceded by a single space; the closing brace occurs on a newline indented to the same level as the block's opening statement. i.e.
int somefunc(int someparam)
{
    int i;
    for (i = 0; i < MAX; i++) {
        ...
    }
}

Incomplete snippet, strictly conforming C90; public domain; past reviewers: none; current reviews: JesseW (cursory);

See also

Personal tools