Using References in C++

There are many online guides to the use of references in C++. We recommend as a starting point the concise thegeekstuff.com page, which defines a reference as "a second name of an existing variable" and explains why it is useful. While several guides give the example of a swap routine, Himanshu Arora's page also shows the code that would have been necessary using pointers.

The following table summarises differences between pointers and references.

Characteristic Pointer Reference
Symbol * &
Syntax for declaration and assignment
int myInt = 99;
int *myPtr = &myInt;    
int myInt = 99;
int &myRef = myInt;    
Syntax for parameter
#include <stdio.h>

void increment(int *num)
{
  (*num)++;
}

int main()
{
  int myInt = 99;  
  increment(&myInt); // Passing address directly
  printf("myInt after increment: %d\n", myInt);

  return 0;
}    
#include <stdio.h>

void increment(int &num)
{
  num++;
}

int main()
{
  int myInt = 99;
  increment(myInt);
  printf("myInt after increment: %d\n", myInt);

  return 0;
}   
Dereferencing necessary to obtain value ... Yes No
... hence "clean code" No Yes
Reassignment possible Yes No
Can point to NULL Yes No
Memory management by compiler No Yes
Address accessible Yes No
Available in C Yes No
Programming - a skill for life!

How to apply your knowledge of Pascal when learning C/C++