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.

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s