The unary * operator—commonly referred to as the indirection operator or dereferencing operator—returns an lvalue representing the object to which its pointer operand points. For example (referring again to Fig. 8.2), the statement
cout << *yPtr << endl;
displays the value of variable y
, namely, 5
, just as the statement
cout << y << endl;
would. Using *
in this manner is called dereferencing a pointer. A dereferenced pointer may also be used on the left side of an assignment statement, as in
*yPtr = 9;
which would assign 9
to y
in Fig. 8.3. The dereferenced pointer may also be used to receive an input value as in
cin >> *yPtr;
which places the input value in y
.
Common Programming Error 8.2
Dereferencing an uninitialized pointer results in undefined behavior that could cause a fatal execution-time error. This could also lead to accidentally modifying important data, allowing the program to run to completion, possibly with incorrect results.
Error-Prevention Tip 8.2
Dereferencing a null pointer results in undefined behavior and typically is a fatal execution-time error, so you should ensure that a pointer is not null before dereferencing it.