What are references and how to use them? Use reference as function parameter, relevant examples

Keywords: C++

What is reference?

int a;

int &b=a;

Above is the reference to the variable

Sign & it's not the meaning of going to address, it's the meaning of going to address when it's a pointer, here it's a reference. (this quotation is not a verb, but a noun.)

Definition of reference: a "reference" can be created for a data. Its function is to play an alias for a variable.

int &b=a;

The above declares that b is a reference of a, that is, b is an alias of A.

&The function of the symbol is now called a reference declarator and does not represent an address.

Compare the use of pointers:

int a=30;

int *p=&a;

cout<<*p;

 

 

int a=30;

int &b=a;

cout<<b;

Note: when a reference is declared, it must be initialized at the same time. An alias indicating who he is.

 

Example: get the value of variable by reference.

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

int main(){
    
    int a=10;
    int &b=a;
    a=a*a;
    cout<<a<<setw(6)<<b<<endl;
    b=b/5;
    cout<<b<<setw(6)<<a<<endl;
    
    return 0;
}

Use reference as function parameter

Example: interchange the values of variables i and j.

First of all, look at the procedure of exchange failure:

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

void swap(int a,int b){
    int temp;
    temp=a;
    a=b;
    b=temp;
}

int main(){
    
    int i=3,j=5;
    swap(i,j);
    cout<<i<<" "<<j<<endl;
    return 0;
}

A program that then uses the pointer method to exchange:

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

void swap(int *p1,int *p2){
    int temp;
    temp=*p1;
    *p1=*p2;
    *p2=temp;
}

int main(){
    
    int i=3,j=5;
    swap(&i,&j);
    cout<<i<<" "<<j<<endl;
    return 0;
}

Finally, the program that uses the method of reference to exchange:

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

void swap(int &a,int &b){
    int temp;
    temp=a;
    a=b;
    b=temp;
}

int main(){
    
    int i=3,j=5;
    swap(i,j);
    cout<<"i="<<i<<" "<<"j="<<j<<endl;
    return 0;
}

Posted by 00tank on Sun, 24 May 2020 08:14:12 -0700