Main Content

Variables and pointers and references - C and C++

Archive - Originally posted on "The Horse's Mouth" - 2009-01-23 14:58:49 - Graham Ellis

If I have a variable called "weight" that contains a float, I can use and set its value by using that name.

Pointers

If - in C or in C++ - I declare a variable to be a pointer then that variable may contain a memory address ... I use a * in my type declaration, and then I use & in my assignment:
float * pweight = &weight;

I can then say that I want to use the contents of that variable by preceeeding the name with * in my code, for example:
cout << "www " << *pweight << endl;

References

In C++ only, I can also declare a variable to be a reference by using an & in my declaration:
float & rweight = weight;

A reference gives a variable a second name, and once it has been assigned the variable can be directly accessed by that new name without any extra characters, for example:
cout << "xxx " << rweight << endl ;

References are a commonly used and useful way of giving a variable a second and temporary name without the undue complexity that's imposed by pointers. There are, however, times that you can't do without pointers!

Here's an example of a complete demonstration program:

#include <iostream>
using namespace std;
int main () {
  float weight = 16.8;
/* Pointer */
  float * pweight = &weight;
  cout << "www " << *pweight << endl;
/* Reference */
  float & rweight = weight;
  cout << "xxx " << rweight << endl ;
/* Direct Access */
  cout << "yyy " << weight << endl ;
/* Each of these alters the same variable */
  rweight = rweight + 14.7;
  weight = weight + 3.75;
  *pweight = *pweight + 4.9;
  cout << "zzz " << weight << endl ;
}


Note, specially, how the final three assignments all add to the same variable, but it's referenced in three different ways ... calculating 16.8 + 14.7 + 3.75 + 4.9 when all added together comes to 40.15:

[trainee@easterton lp]$ ./prd
www 16.8
xxx 16.8
yyy 16.8
zzz 40.15
[trainee@easterton lp]$