# Explain C + + references in detail

Time：2021-9-11

## What is a C + + reference

A C + + reference is an alias for an existing variable.

## The meaning of C + + reference

1. In some cases, C + + references can replace pointers.
2. Compared with pointers, references can improve code readability.
Example 1 refers to as a function parameter:

``````//Two number exchange, using pointer
void swap1(int *a,int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}``````
``````//Two number exchange, using reference (reference as parameter)
void swap2(int &a,int &b)
{
int temp = a;
a = b;
b =temp;
}``````
``````int main() {
int c =10;
int d = 100;
swap1(&c,&d);
cout<<c<<","<<d<<endl;
swap2(c,d);
cout<<c<<","<<d<<endl;
return 0;
}``````

Output results

``````100,10
10,100``````

Example 2 refers to as the return value of the function:

``````#include <iostream>
using namespace std;

int nums = {1,2,3,4,5};

//Use reference as function return value
int& SetNum1(int i)
{
int &temp = nums[i];
return temp;
}

//Use pointer as function return value
int* SetNum2(int i)
{
int *temp = &nums[i];
return temp;
}

int main() {
SetNum1(1) = 10*1;
SetNum1(4) = 10*4;
for (int i =0 ; i<5; i++)
cout<<nums[i]<<endl;
*SetNum2(1) = 100 *1;
*SetNum2(4) = 100 *4;
for (int i =0 ; i<5; i++)
cout<<nums[i]<<endl;
}``````

Output:

``````1
10
3
4
40
1
100
3
4
400
``````

As can be seen from the above examples, it is obviously better to implement the same function in terms of readability.

## Does the reference occupy memory space

``````#include <iostream>
using namespace std;

int main() {
int a=10;
int& b=a;
Cout < < "the memory space occupied by reference B is:" < sizeof (b) < < endl;
char c = 'a';
char &d = c;
Cout < < "the memory space occupied by referencing C is:" < sizeof (c) < < endl;
return 0;
}``````

Output:

``````Memory space occupied by reference B: 4
Memory space occupied by reference C: 1``````

## Nature of reference

C + + reference is actually a pointer constant in nature (it is not difficult to explain why int reference occupies 4 bytes of memory space and char reference occupies 1 byte, because int pointer occupies 4 bytes of memory and char pointer occupies 1 byte).

## matters needing attention

When a function returns a reference:
1. If the stack variable is returned, the function return cannot be used as the initial value of other references and cannot be used as an lvalue. (because after the function call, the local variables in the function are destroyed, and the reference (pointer constant) returned by the function will become a “pointless” reference (pointer).
2. If a static variable or global variable is returned, the function returns the initial value that can be used as other references, and can be used as either an lvalue or an lvalue. (because of static variables or global variables, the program runtime always exists, from the beginning of the program to the end of the program).