Programming style is definitely a project-to-project, author-to-author thing. Rarely do two projects share the exact same style unless the original authors are the same; even then, having consistency within a single project is sometimes a mythical goal that never quite gets achieved unless the maintainers keep a watchful eye on all incoming code.

Some projects try hard to document some sort of standard. For a few examples, we have the GNU Coding Standards, the Linux kernel coding style document, and the project I work most on, pacman, has a HACKING file documenting a few style guidelines.

However, this blog post isn't going to cover much of the typical programming style bullet points:

  • Indentation- width and tabs vs. spaces
  • Line length and wrapping
  • Vertical alignment- variable declarations, function prototypes
  • Whitespace within a line- after keywords, around arithmetic operators, comparison operators, assignment operators, commas, etc.
  • Brace placement in languages that need them
  • Naming conventions
  • Comment style, verbosity, and contents

Instead, let's focus on a convention that is rarely stated in a coding style manifesto: arithmetic ordering.

array[foo * 2 + 1] = 6;
value = (value << 3) * 5 + 18;


array[2 * foo + 1] = 6;
value = 18 + 5 * (value << 3);

My gut and eyes tell me that most people use the former forms in coding rather than the latter. An argument for the second form comes with this math expression: 2x + 1 as opposed to x2 + 1, which no one would ever use. However, this isn't the preferred form. This is rather interesting, and my guesses are the following:

  • Most programmers tend to put the variable on the left-hand side of comparisons: a < 2 rather than 2 > a, for example. The same logic holds here.
  • It reads better left-to-right. "take foo, double it, add one" rather than "take two, multiply by foo, add one".
  • In typed languages, having the variable rather than the constant first allows you to more quickly deduce the resulting type.

Are there other implicit conventions you have come across in code? I'd love to hear them.