C + + Basics: C + + references


A reference variable is an alias, that is, it is another name for an existing variable. Once a reference is initialized to a variable, you can use the reference name or variable name to point to the variable.

C + + reference vs pointer

References are easily confused with pointers. There are three main differences between them:

  • There is no empty reference. The reference must be connected to a valid piece of memory.
  • Once a reference is initialized as an object, it cannot be pointed to another object. A pointer can point to another object at any time.
  • References must be initialized at creation time. Pointers can be initialized at any time.


C/C++Learning skirt [712]   two eight four   seven zero five  】, whether you areXiaobai is still an advanced person, whether you want to change your career or join it, you can learn about it, make progress together and learn together! There are development tools in the skirt, and many dry goods and technical data are shared!

Creating references in C + +

Imagine that the variable name is the label attached to the memory location of the variable. You can think of the reference as the second label attached to the memory location of the variable. Therefore, you can access the contents of the variable through the original variable name or reference. For example:

int i = 17;

We can declare reference variables for I, as follows:

int&  r = i;
double& s = d;


In these statements, & readquote。 Therefore, the first declaration can be read as “R is an integer reference initialized to I”, and the second declaration can be read as “s is a double reference initialized to D”. The following example uses int and double References:


using namespace std;
int main ()
   //Declare simple variables
   int    i;
   double d;
   //Declare reference variables
   int&    r = i;
   double& s = d;
   i = 5;
   cout << "Value of i : " << i << endl;
   cout << "Value of i reference : " << r  << endl;
   d = 11.7;
   cout << "Value of d : " << d << endl;
   cout << "Value of d reference : " << s  << endl;
   return 0;

When the above code is compiled and executed, it will produce the following results:

Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7

References are usually used for function parameter lists and function return values. Here are two important concepts related to C + + references that C + + programmers must be aware of: