10. Whitespace

The following rules have been found to improve readability — not for the compiler, but for the humans that need to understand what they are reading — the quicker the better. Peripheral vision plays a role in this, and this is where correct use of whitespace is a valuable asset to code readability.

  1. Each of the keywords if, while, for, switch, and return, shall be followed by one space when there is additional program text on the same line.

  2. Each of the assignment operators and binary operators are always preceded and followed by one space.

  3. Each of the unary operators +, -, ++, --, !, and ~, shall be written without a space on the operand side.

  4. Pointer operator * shall be written with whitespace on each side within declarations (variables and arguments), but without a space when performing reads or writes.

  5. The ? and : characters that comprise the ternary operator shall each always be preceded and followed by 1 space unless it is is the first character on the line.

  6. The structure pointer and structure member operators (-> and ., respectively) shall always be without surrounding spaces.

  7. Left and right brackets of the array subscript operator ([ and ]) shall be without surrounding spaces, except as required by another whitespace rule.

  8. Expressions within parentheses shall always have no spaces adjacent to the left and right parentheses characters.

    Exception: nested parentheses: the outer-most parentheses has no space within it, but then every other nested inner parentheses has a single space on its inside to improve readability — it makes it quicker for the eye to identify what is nested.

  9. Left and right parentheses of function calls shall always be without surrounding spaces. Exception: sometimes in long lists of function prototypes, column alignment of the list of arguments can sometimes serve to quickly show an argument pattern than holds among a group of functions. In this case, space after the function name and before the opening parenthesis to align all the opening parentheses is acceptable. See this example.

  10. Commas separating function arguments shall always be followed by one space, except when the arguments are organized in a vertical list (for readability) and the commas then appear at the end of the line.

  11. Each semicolon separating the elements of a for statement shall always be followed by two spaces for improved readability, except when used as the head of an endless loop like this:

    for (;;) {...}
    
  12. Each semicolon terminating a statement shall not have a preceding space. Exception: sometimes lists of things can be made more readable (i.e. to see there are no bugs at a glance) when the ; at the end of each list item is aligned. In this case only, preceding whitespace before the ; is accepted.

Further Reading