- Use spaces to indent. Two Spaces.
- Function definitions — open and close braces should be on lines by themselves.
void foo()
{
// do stuff
}
- Other braces, including for, while, do, switch statements and class definitions — the open brace should go on the same line as the control structure.
for (int i = 0; i < 10; i++) {
// do stuff
}
- If/else statements — as above, but if there is an else clause, the close brace should go on the same line as the else.
if (timeToGetCoffee) {
buyCoffee(&coffee);
chugIt(coffee);
} else if (timeToGoHome)
// comment on else case
outtaHere = true;
- Function declarations and calls — do not use any spaces between the name and the open paren, inside the parentheses, or before commas that separate arguments. Do use a single space after commas that separate arguments.
int myFunction(int arg1, float arg2);
void noArgFunction(); // for C++ or Objective-C++
void noArgFunction(void); // for C or Objective-C
- In C++, the null pointer value should be written as
0.
- Tests for null pointers, false values and 0 values should all be done directly, not through an inequality or equality comparison.
if (foo->isSomething()) {
// code
}
// test for false
if (!foo->isSomething()) {
// code
}
// test for non-null
if (ptr) {
// code
}
// test for null
if (!ptr) {
// code
}
// test for nonzero
if (count) {
// code
}
// test for zero
if (!count) {
// code
}
- With very few exceptions, prefer embedded capitals instead of underscores for class, function and variable names.
- C++ and Objective-C classes, interfaces and protocols, and other type names — these names should start with a capital letter and use InterCaps.
class MyImportantClass;
- Local variables should use interCaps, but the first word should start with a lowercase letter, like this:
int myInt;
- C++ data members should be named like local variables, but with a prefix of m_.
- C++ member functions should follow the same naming convention as free functions.
- Enum members should user InterCaps with an initial capital letter.
- #defined constants should use all uppercase names with words separated by underscores.
- Constructors for C++ classes should initialize all of their members using C++ constructor synatax. Each member (and superclass) should be indented on a separate line, with the colon or comma preceding the member on that line.
MyClass::MyClass(Document* doc)
: MySuperClass()
, m_myMember(0)
, m_doc(doc)
{
}
MyOtherClass::MyOtherClass()
: MySuperClass()
{
}
[ Source ]