C++ USES references or Pointers as function arguments

  • 2020-04-02 02:23:05
  • OfStack

C++ added the reference type, mainly as a function parameter, in order to expand the function of passing data, more secure than pointer parameters intuitive. When passing a reference as an argument, the argument initializes the parameter without allocating memory space or calling the copy constructor, thus improving the performance of the operation. So we should use references instead of Pointers whenever possible, but be aware that because local variables have their own short life cycle, it is not possible to return a reference to a local variable.

A reference is usually initialized when it is defined, but when it is used as an argument, it is initialized when it is called. The change to the reference is the change to the referenced variable.

References to variables are direct access, Pointers are indirect access, Pointers have their own independent address and memory space, references are the alias of variables no independent memory space.

Pass a pointer to a variable


//The parameter is a pointer variable, the argument is the address of a variable, when the function is called, the parameter (pointer variable) points to the real parameter unit 。
//By using pointer variables as parameters, the function can realize the interchangeability of the values pointed to by two pointer variables.
#include <iostream>
using namespace std;
int main( )
{   void swap(int *,int *);
    int i=3,j=5;
    swap(&i,&j);                            //An argument is the address of a variable
    cout<<i<<"  "<<j<<endl;                 //The values of I and j have been swapped
    return 0;
}
void swap(int *p1,int *p2)                 //A parameter is a pointer variable
{   int temp;
    temp=*p1;                              //The following three lines are used for interchanging the values of I and j
    *p1=*p2;
    *p2=temp;
}

Using "reference parameter" to realize the value interchange of two variables


#include <iostream>
using namespace std;
int main( )
{   void swap(int &,int &);
    int i=3,j=5;
    swap(i,j);
    cout<<"i="<<i<<"  "<<"j="<<j<<endl;
    return 0;
}
void swap(int &a,int &b)      //A parameter is a reference type that is initialized when a function is called
{   int temp;
    temp=a;
    a=b;
    b=temp;
}
//The output result is
// i=5 j=3


< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/20140504110253.jpg? 20144411314 ">


Related articles: