[untitled] Pointer passing and reference passing in parameter passing

Value transfer:

A formal parameter is a copy of an argument. Changing the value of a formal parameter does not affect the value of an external argument. From the perspective of the called function, the value transfer is one-way (argument - > formal parameter), and the value of the parameter can only be passed in,

Cannot transfer out. When the parameter needs to be modified inside the function and you don't want this change to affect the caller, value passing is used.

Pointer passing:

A formal parameter is a pointer to the address of the argument. When pointing to a formal parameter, it is equivalent to the operation on the argument itself

Reference passing:

The formal parameter is equivalent to the "alias" of the argument. The operation on the formal parameter is actually the operation on the argument. In the process of reference passing, although the formal parameters of the called function are also stored on the stack as local variables

Memory space is opened up in, but at this time, the address of the argument variable put in by the calling function is stored. Any operation of the called function on the formal parameter is treated as indirect addressing, that is, through

The address stored in the stack accesses the argument variable in the calling function. Because of this, any operation of the called function on the formal parameter affects the argument variable in the main calling function.

The following code explains this in detail (it explains the essence of the problem from the point of view of the address of arguments and formal parameters in memory, which is easy to understand)

#include<iostream>
using namespace std;
//pass by value
 void change1(int n){
    cout<<"pass by value--Function operation address"<<&n<<endl;         //The address of the copy is displayed instead of the source address 
    n++;
}

//Reference passing
void change2(int & n){
    cout<<"Reference passing--Function operation address"<<&n<<endl; 
    n++;
}
 //Pointer passing
void change3(int *n){
     cout<<"Pointer passing--Function operation address "<<n<<endl; 
    *n=*n+1;
 } 
int     main(){
    int n=10;
    cout<<"Address of argument"<<&n<<endl;
    change1(n);
    cout<<"after change1() n="<<n<<endl;
    change2(n);
    cout<<"after change2() n="<<n<<endl;
    change3(&n);
    cout<<"after change3() n="<<n<<endl;
    return true;
}

So, what's the difference between reference passing and pointer passing?

Referenced rules:
(1) References must be initialized as they are created (pointers can be initialized at any time).

(2) There can be no NULL reference. The reference must be associated with a legal storage unit (the pointer can be NULL).
(3) Once the reference is initialized, the relationship of the reference cannot be changed (the pointer can change the object at any time).

The essence of pointer passing:

Pointer passing parameter is essentially a way of value passing. What it passes is an address value. In the process of value transfer, the formal parameters of the called function are treated as local variables of the called function,

That is, a memory space is opened up in the stack to store the value of the argument put in by the main calling function, so as to become a copy of the argument. The characteristic of value transfer is the effect of the called function on the formal parameters

Any operation is performed as a local variable and will not affect the value of the argument variable of the main calling function. (this is to say that the address value of the argument pointer itself will not change.) if you can't understand it, you can skip this paragraph

Pointer passing and reference passing are generally applicable to:

Modify parameters inside the function and want the changes to affect the caller. Compared with pointer / reference passing, the change can be "passed" from the formal parameter to the argument (in fact, it can be modified directly in the memory of the argument,

Unlike value passing, the value of the argument is modified by copying it to another memory address.

Another usage is: when a function actually needs to return multiple values, but can only explicitly return one value, the variables that need to be returned can be passed as pointers / references

If the function is modified and returned inside the function, the caller can get the variable after modification, which is also equivalent to an implicit return value.

The following is a very good article on pointers and citations. You can refer to the original source address: http://xinklabi.iteye.com/blog/653643

Conceptually. In essence, a pointer is a variable that stores a variable address. It is logically independent. It can be changed, including the change of the address it points to and the change of the data stored in the address it points to.

The reference is an alias, which is not logically independent. Its existence is dependent, so the reference must be initialized at the beginning, and the referenced object cannot be changed in its whole life cycle (it can only be attached to the same variable from beginning to end).

In C + +, pointers and references are often used for parameter passing of functions. However, pointer passing parameters and reference passing parameters are essentially different:

Pointer passing parameter is essentially a way of value passing. What it passes is an address value. In the process of value transfer, the formal parameters of the called function are treated as the local variables of the called function, that is, a memory space is opened up in the stack to store the values of the arguments put in by the main calling function, thus becoming a copy of the arguments. The characteristic of value transfer is that any operation of the called function on the formal parameters is carried out as a local variable and will not affect the value of the argument variable of the main calling function. (this means that the address value of the argument pointer itself will not change)

In the process of reference transfer, although the formal parameters of the called function also open up memory space in the stack as local variables, what is stored at this time is the address of the argument variable put in by the calling function. Any operation of the called function on the formal parameters is treated as indirect addressing, that is, the actual parameter variables in the calling function are accessed through the address stored in the stack. Because of this, any operation of the called function on the formal parameter affects the argument variable in the main calling function.

Reference passing and pointer passing are different. Although they are a local variable in the called function stack space, any processing of reference parameters will operate on the relevant variables in the calling function through an indirect addressing method. For the parameters passed by the pointer, if you change the pointer address in the called function, it will not affect the relevant variables of the calling function. If you want to change the related variables in the calling function through pointer parameter passing, you have to use a pointer to the pointer or pointer reference.

In order to further deepen the differences between pointers and references, I will explain the differences between them from the perspective of compilation:

When compiling, the program adds pointers and references to the symbol table, which records the variable name and the address corresponding to the variable. The address value corresponding to the pointer variable on the symbol table is the address value of the pointer variable, and the address value corresponding to the reference on the symbol table is the address value of the reference object. After the symbol table is generated, it will not be changed. Therefore, the pointer can change the object it points to (the value in the pointer variable can be changed), while the reference object cannot be modified.

Finally, summarize the similarities and differences between pointers and References:

★ similarities:

● all are the concept of address;

The pointer points to a piece of memory, and its content is the address of the memory; A reference is an alias for a block of memory.

★ differences:

● the pointer is an entity, while the reference is only an alias;

● the reference can only be initialized once during definition, and then cannot be changed; Pointer variable; By quoting "from the beginning to the end", the pointer can "change when seeing different things";

● the reference has no const, the pointer has const, and the pointer of const is immutable; (specifically, there is no form of int & const a, while const int & A is available. The former means that the reference itself, that is, the alias, cannot be changed, which is of course, so this form is not required, and the latter means that the value referred to by the reference cannot be changed)

● the reference cannot be null, and the pointer can be null;

● "sizeof reference" gets the size of the pointed variable (object), while "sizeof pointer" gets the size of the pointer itself;

● the meaning of self increment (+) operation of pointer and reference is different;

● references are type safe, not pointers (references have more type checks than pointers)

/*1, Referenced concepts

Reference introduces a synonym for an object. Defining a reference is represented in a similar way to defining a pointer, except that & is used instead of *.
For example: Point pt1(10,10);
Point &pt2=pt1; Defines a reference where pt2 is pt1. With this definition, pt1 and pt2 represent the same object.
It should be emphasized that reference does not produce a copy of the object, but only a synonym of the object. Therefore, when the following statement is executed:
pt1.offset(2,2);
pt1 And pt2 have values of (12, 12).
A reference must be initialized as soon as it is defined because it must be synonymous with something. You can't define a reference first
 Initialize it. For example, the following statement is illegal:
Point &pt3;
pt3=pt1;
So since reference is only a synonym for something, what is its purpose?
The two main uses of references are discussed below: as function parameters and returning lvalues from functions. 

2, Reference parameters

1,Pass variable parameters
 In traditional c, when a function is called, the parameters are passed by values, which means that the parameters of the function do not have the ability to return values.
Therefore, in traditional c, if the function parameters need to have the ability to return values, they are often realized through pointers. For example, implement
 The c procedure for exchanging the values of two integer variables is as follows:*/
void swapint(int *a,int *b)
{
int temp;
temp=*a;
a=*b;
*b=temp;
}

//After using the reference mechanism, the c + + version of the above program is:
void swapint(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
//The c + + method to call this function is: swapint (x,y); c + + automatically passes the addresses of X and y as parameters to the swapint function.

/*2,Passing large objects to functions
 When a large object is passed to a function, the use of reference parameters can improve the efficiency of parameter passing, because references do not produce the effect of the object
 Copy, that is, when parameters are passed, objects do not need to be copied. The following example defines a class of a finite set of integers:*/ 
const maxCard=100; 
Class Set 
{
int elems[maxCard]; // maxCard represents the maximum number of elements in the set. 
int card; // Number of elements in the collection. 
public:
Set () {card=0;} //Constructor
friend Set operator * (Set ,Set ) ; //Overloaded operation symbol *, used to calculate the intersection of sets, using objects as value passing parameters
friend Set operator * (Set & ,Set & )/*Overloaded operation symbol *, which is used to calculate the intersection of sets, and uses the reference of the object as the value passing parameter */
...
}
//First consider the implementation of set intersection
Set operator *( Set Set1,Set Set2)
{
Set res;
for(int i=0;i<Set1.card;++i)
for(int j=0;j>Set2.card;++j)
if(Set1.elems[i]==Set2.elems[j])
{
res.elems[res.card++]=Set1.elems[i];
break;
}
return res;
}
Since overloaded operators cannot operate on pointers alone, we must declare operands as Set Type instead of Set * . 
Each use*When doing intersection operation, the whole set is copied, which is very inefficient. We can use citation to avoid this situation.
Set operator *( Set &Set1,Set &Set2)
{ Set res;
for(int i=0;i<Set1.card;++i)
for(int j=0;j>Set2.card;++j)
if(Set1.elems[i]==Set2.elems[j])
{
res.elems[res.card++]=Set1.elems[i];
break;
}
return res;
}

/*3, Reference return value

If a function returns a reference, the call to the function can also be assigned. Here is a function that takes two reference parameters and returns a reference to a double:*/
double &max(double &d1,double &d2)
{
return d1>d2?d1:d2;
}
//Since the max() function returns a reference to a double, we can use max() to add 1 to the larger double:
max(x,y)+=1.0;

Keywords: C++

Added by ScoTi on Sun, 16 Jan 2022 16:17:44 +0200