C++ Style Guide

Version 6 (Trond Lossius, 2012-11-24 09:33 pm)

1 1 Tim Place
h1. C++ Style Guide
2 1 Tim Place
3 1 Tim Place
4 1 Tim Place
h2. Naming Conventions
5 1 Tim Place
6 3 Trond Lossius
h3. Variable Naming
7 3 Trond Lossius
8 6 Trond Lossius
This serves to indicate the scope of the variable:
9 4 Trond Lossius
10 5 Trond Lossius
* @kSomething@ is a constant
11 5 Trond Lossius
* @gSomething@ is a global
12 5 Trond Lossius
* @mSomething@ is a member of a class 
13 5 Trond Lossius
* @aSomething@ is an argument (could also use an rather than a for grammar reasons depending on what comes next)
14 5 Trond Lossius
* @something@ is a local
15 5 Trond Lossius
* @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
16 1 Tim Place
17 1 Tim Place
h3. Message Naming
18 1 Tim Place
19 1 Tim Place
Be as unambiguous as possible.
20 1 Tim Place
21 1 Tim Place
Example:
22 1 Tim Place
23 2 Tim Place
> 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?
24 1 Tim Place
25 1 Tim Place
26 1 Tim Place
27 1 Tim Place
h2. C++ Syntax Conventions
28 1 Tim Place
29 1 Tim Place
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.
30 1 Tim Place
31 1 Tim Place
h3. if/else
32 1 Tim Place
33 1 Tim Place
The <code>if</code> 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 <code>else</code> clause.
34 1 Tim Place
35 1 Tim Place
The opening brace should be on the same line as the <code>if</code> keyword unless the condition is long and it becomes clearer to do otherwise.
36 1 Tim Place
37 1 Tim Place
The closing braces should always be on their own line and with proper indentation.
38 1 Tim Place
39 1 Tim Place
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.
40 1 Tim Place
41 1 Tim Place
Example:
42 1 Tim Place
<pre>
43 1 Tim Place
  if (condition) {
44 1 Tim Place
    // some code
45 1 Tim Place
  }
46 1 Tim Place
  else {
47 1 Tim Place
    // some code
48 1 Tim Place
  }
49 1 Tim Place
</pre>