« Previous - Version 5/6 (diff) - Next » - Current version
Trond Lossius, 2012-11-24 09:32 pm


C++ Style Guide

Naming Conventions

Variable Naming

This aserves to indicate the scope of the variable:

  • kSomething is a constant
  • gSomething is a global
  • mSomething is a member of a class
  • aSomething is an argument (could also use an rather than a for grammar reasons depending on what comes next)
  • something is a local
  • sSomething for a static. E.g., static int sSomething = 0; that acts like a global but is only available to that specific file and to no other files

Message Naming

Be as unambiguous as possible.

Example:

You want to get the names of all of the attributes of an object. You could name this "getAttributes". Unfortunately, this is ambiguous. Does it mean to get the Attribute objects? The attribute names? The attribute values? It should be instead be named "getAttributeNames", because it is returning the names of the attributes. Perhaps it should be even more specific, indicating which attribute names it is getting: is it getting all of them? just some of them? just those that are current?

C++ Syntax Conventions

In C/C++ your code can end up looking like almost anything given the flexibility that is afforded with whitespace and other "decorative" code. While these rules are not hard and fast, it will make it easiest if every generally follows the same way of formatting common idioms of the language.

if/else

The if condition should be surround by one space on each side (one after the if, one before the opening brace). The should also be a space before the opening brace of the else clause.

The opening brace should be on the same line as the if keyword unless the condition is long and it becomes clearer to do otherwise.

The closing braces should always be on their own line and with proper indentation.

Generally, when using one line statements in an if/else structure it is preferred to eliminate the braces. Sometimes it might, however, be handy to leave them for debugging or other reasons.

Example:

  if (condition) {
    // some code
  }
  else {
    // some code
  }