A C++ Software Development Tip – * = multiply and pointer

When developing C++ code it is very common to declare a pointer to a variable of a specific type (either as a local variable, a class member or (hopefully more rarely) a global variable.

Consider the following two exactly equivalent lines

TMyType *Variable; // no space between the * and the variable – *** preferred ***

TMyType * Variable; // space between the * and the variable

Similarly when using the value pointed to (dereferencing) consider the following two exactly equivalent lines

TMyType X = *Variable; // no space between the * and the variable – *** preferred ***

TMyType X = * Variable; // space between the * and the variable

In each case we prefer the first of the two lines. Why? because the second form looks too much like the multiply operator (z = x * y).

It is very important to be consistent throughout all your code. Knowing that we always use the first form allows us to use a search on “*Variable” and find ALL the instances where the pointer is dereferenced.