Indirection Operator and Dereferencing


The primary use of a pointer is to access and, if appropriate, change the value of the variable that the pointer is pointing to. In the following program, the value of the integer variable num is changed twice.

 #include <iostream> using namespace std; int main () {  int num = 5;  int* iPtr = &num;  cout << "The value of num is " << num << endl;  num = 10;  cout << "The value of num after num = 10 is "   << num << endl;  *iPtr = 15;  cout << "The value of num after *iPtr = 15 is "   << num << endl;  return 0; } 

The resulting output is

 The value of num is 5 The value of num after num = 10 is 10 The value of num after *iPtr = 15 is 15 

The first change should be familiar, by the direct assignment of a value to num, such as num = 10. However, the second change is accomplished a new way, using the indirection operator:

 *iPtr = 15; 

The indirection operator is an asterisk, the same asterisk that you used to declare the pointer or to perform multiplication. However, in this statement the asterisk is not being used in a declaration or to perform multiplication, so in this context it is being used as an indirection operator.

Note  

As mentioned earlier in this chapter, this is another example of a symbol having different meanings in the C++ programming language depending on the context in which it was used.

The placement of the indirection operator before a pointer is said to dereference the pointer. Indeed, some texts refer to the indirection operator as the dereferencing operator. The value of a dereferenced pointer is not an address, but rather the value at that address ”that is, the value of the variable that the pointer points to.

For example, in the preceding program, iPtr s value is the address of num. However, the value of iPtr dereferenced is the value of num. Thus, the following two statements have the same effect, both changing the value of num:

 num = 25;    *iPtr = 25; 

Similarly, a dereferenced pointer can be used in arithmetic expressions the same as the variable to which it points. Thus, the following two statements have the same effect:

 num *= 2;    *iPtr *= 2; 

In these examples, changing a variable s value using the indirection operator rather than through a straightforward assignment seems like an unnecessary complication. However, there are instances covered later in this chapter, such as looping through an array using a pointer, or using dynamic memory allocation, in which using the indirection operator is helpful or even necessary.




C++ Demystified(c) A Self-Teaching Guide
C++ Demystified(c) A Self-Teaching Guide
ISBN: 72253703
EAN: N/A
Year: 2006
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net