Skip to the content of the web site.

Lesson 208: Why int *p_data and not int * p_data or int* p_data?

Previous lesson Next lesson


Up until this point, you will have noticed that every single time we declared a pointer (that is, a variable storing an address), we always used the notation:

	double   *p_data;
	Vector2D *p_points;

In Lesson 152, we saw that white space really doesn't matter, so all of these are valid:

	double *p_data;
	double * p_data;
	double* p_data;
	double*p_data;

	double
	      *
	       p_data;

Why then, do we almost religiously use the first notation and never any of the others?

  1. First, * for de-referencing a pointer is a unary operator, and for all other unary operators, we have always juxtaposed that operator with the operand.
  2. Second, the notations double*p_data and double * p_data, looks more like multiplication.
  3. Finally, double* p_data looks as if the * is associated with the type. It isn't.

The last, while common, is deceiving. Consider the following two declarations:

	double *p_data, p_center;

and

	double* p_data, p_center;

The question is: is p_center a pointer to a double (as the choice of name suggests), or just a double?

Unfortunately, if you believed the naming convention, this would be a semantic error: p_center would actually be declared as a double while p_data would be declared to be a pointer to a double. The correct declaration would be:

	double *p_data, *p_center;

Note that this is what the developers of C originally envisioned:

The declaration double *p_value indicates that to get a double (the type), it will be necessary to de-reference whatever p_value is assigned.

While you are welcome to use any notation you wish (white space doesn't matter), please consider continuing to use the notation we suggest so that a user reading

	double* p_data, center;

does not accidentally believe that center is being declared as a pointer to a double.


Previous lesson Next lesson