Pointers and references

From Rosetta Code
Revision as of 19:09, 26 January 2007 by MikeMol (talk | contribs) (Moved to Language Features category, simplified task description. (It was too specific))

Template:Language Features

In this task, the goal is to desmonstrate common operations on pointers and references.

C++

With pointers:

The following code creates a pointer to an int variable

 int var = 3;
 int* pointer = &var;
 // or alternatively:
 int* pointer2(&var);

Access the integer variable through the pointer:

 int v = *pointer; // sets v to the value of var (i.e. 3)
 *pointer = 42; // sets var to 42

Change the pointer to refer to another object

 int othervar;
 pointer = &othervar;

Change the pointer to not point to any object

 pointer = 0;
 // or alternatively:
 pointer = NULL;

Get a pointer to the first element of an array:

 int array[10];
 pointer = array;
 // or alternatively:
 pointer = &array[0];

Move the pointer to another object in the array

 pointer += 3; // pointer now points to array[3]
 pointer -= 2; // pointer now points to array[1]

Access another object in the same array through the pointer

 v = pointer[3]; // accesses third-next object, i.e. array[4]
 v = pointer[-1]; // accesses previous object, i.e. array[0]
 // or alternatively
 v = *(pointer + 3); // array[4]
 v = *(pointer - 1); // array[0]

With references:

The following code create a reference to an int variable:

 int var = 3;
 int& ref = var;
 // or alternatively:
 int& ref2(var);

Access the integer variable through the reference

 int v = ref; // sets v to the value of var, that is, 3
 ref = 42; // sets var to 42

References cannot be changed to refer to other objects, and cannot (legally) made to refer to no object.

Get a reference to the first element of an array:

 int array[10];
 int& ref3 = array[0];

Changing the reference to refer to another object of the array is not possible.

Accessing another object of the array through the reference:

 v = (&ref)[3]; // read value of array[3]; however doing this is bad style