Operators

Address-of and Dereference Operator Rules

Consider the * and & operators as part of the type, and declare types as demonstrated below.

const std::vector<int>& referenceToVector = otherVector;
const ComplexType* pointerToComplexType = &otherComplexType;
void foo (const Bar& bar);

Yes - we know that many people would argue that a more technically correct layout for such a declaration would be:

SomeObject *myObject = getAPointer();
SomeObject &myObject = getAReference();

But we think it makes more sense for the asterisk to stick to the type name, because the pointer-ness is a quality that belongs to the type, not to the variable. The only time that this can lead to any confusion is when you're declaring multiple pointers of the same type in the same statement – which leads on to the next rule.

When declaring multiple pointers or references of the same type that involve the asterisk or ampersand character, never do so in a single statement, e.g.

SomeObject* p1, *p2;

instead split them out onto separate lines and write the type name again, to make it quite clear what's going on, and avoid the danger of missing out any vital asterisks.

SomeObject* p1;
SomeObject* p2;

Or better still, use a smart-pointer or typedef to create a type-name that doesn’t require the asterisk or ampersand!

General Operator Rules

Put a single space before and after free-standing operators.

int a = 1, b = 2;
const int c = a + b;
int a = 1;
a += 1;
a <<= 1;
int a = 0;
for (int i = 0; i < 100; ++i)
    a = i;

Increment and Decrement Operators

Pre-increment and pre-decrement operators are always to be preceded by a space, but not followed by one.

int a = 0;
for (int i = 0; i < 100; ++i)
    a = i;

Post-increment and post-decrement operators are not to have a space preceding or following them.

int a = 0;
a--;

runSomething (a++);

General Rules

Always use pre-increment and pre-decrement operators unless the conditions warrant a post-increment or post-decrement operator.

for (int i = 0; i < 100; ++i)
    doSomething();

Not-Operator Rules

Always insert a space after the NOT-operator, but never before.

if (! someCondition)
{
    //Do something important.
}

Custom Operators

When defining custom operators, the symbol must be attached to the keyword operator, followed by a space before the opening parenthesis.

//As a method of a class or struct:
bool operator== (const Type& other) const;