Revision 6 as of 2014-08-26 22:49:42

Clear message

Back to developer page.

C++ coding conventions and style guide

We try to maintain a consistent coding style because it makes reading and modifying the code easier. Our coding conventions aren't necessarily better than others (though we try to follow ones that make sense and change those that don't), but the main utility of this is consistency.

We're much stricter these days than we were, say, 10 years ago. The reason for this is that a codebase with many contributors and large size is much harder to maintain than a small one. So new code must pass tougher tests than some of the existing code. (Of course, the existing code should ideally be cleaned up more, too, but few people are motivated to work on such tasks if there are other things to do that seem more urgent.) Once code is in, it usually isn't changed for years unless we discover a bug. So we really try to put a lot of effort on making things as right as possible on the first try.

The following is not meant to be a complete description of our coding conventions. When in doubt, follow the example of the existing code.

See also the information on how and where to put ../Whitespace.

General recommendations

We generally follow the recommendations in the book C++ Coding Standards: 101 Rules, Guidelines, and Best Practices by Herb Sutter and Andrei Alexandrescu. In the tracker or elsewhere, a mark of the form [SA x] is a reference to a rule in that book. For example, [SA 9] refers to Sutter and Alexandrescu's rule 9: "Don’t pessimize prematurely".

Comments

   1 // Write complete sentences ending with periods.
   2 
   3 // Use imperative if possible: "Return the factorial." is better than "Returns the factorial.".
   4 
   5 // Leave a space between the slashes and the comment.
   6 
   7 /*
   8   Use this style for comments
   9   spanning over multiple
  10   lines and keep in mind that
  11   "the best kind of comments are the ones you don't need"
  12   (http://blog.codinghorror.com/code-tells-you-how-comments-tell-you-why/).
  13 */

Namespaces

Header file guards

Macro names for header file guards follow this algorithm:

Example: learning/state_space_sample.h becomes LEARNING_STATE_SPACE_SAMPLE_H.

Guard blocks should look like this:

   1 #ifndef LEARNING_STATE_SPACE_SAMPLE_H
   2 #define LEARNING_STATE_SPACE_SAMPLE_H
   3 // ...
   4 #endif
   5 

That's all. In particular, don't add comments to the preprocessor directives and don't add further underscores.

Function signatures

Anti-idioms