当前位置:网站首页>Three ways of function parameter transfer in C language
Three ways of function parameter transfer in C language
2022-07-02 18:37:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
C There are three ways to transfer function parameters in language
(1) Pass value , Is to pass the value of your variable to the formal parameter of the function , In fact, a new formal parameter is generated with the value of the variable , Therefore, the change of parameters in the function will not affect the value of variables outside the function . (2) Byref , Is to pass the address of the variable to the pointer of the formal parameter in the function , Make the pointer point to the address of the real variable , Because the change of the content of the address indicated by the pointer can be reflected outside the function , That is, it can change the value of variables outside the function . (3) The reference , It is actually realized through pointers , It can achieve the effect of use, such as address transmission , However, the use method is such as value transmission . Say a few suggestions : If the value is passed , New objects are generated , Spend time and space , When you exit a function , The object will be destroyed again , Spend time and space . So if int,char Equivalent intrinsic type , It's your own class or structure, etc , It is recommended to pass pointers or references , Because they don't create new objects .
example 1: The output of the following code is : #include<stdio.h> void change(int*a, int&b, int c) { c=*a; b=30; *a=20; } int main ( ) { int a=10, b=20, c=30; change(&a,b,c); printf(“%d,%d,%d,”,a,b,c); return 0; } result :20 30 30
analysis : This question examines the problem of function parameter transfer . 1, The pointer passes the parameter -> Pass the address of the variable directly into the function , Function can modify its value . 2, Reference and reference -> Pass a reference to a variable into a function , The effect is the same as the pointer , Similarly, its value can be modified in the function . 3, It's worth passing on -> In the process of parameter transfer , First of all, will c Copy the value of to the function c Variable , Then what is modified in the function is the function c Variable , Then when the function returns , The system automatically releases variables c. And yes main Functional c No impact .
example 2: #include<stdio.h> void myswap(int x, int y) { int t; t=x; x=y; y=t; } int main() { int a, b; printf(“ Please enter two integers to be exchanged :”); scanf(“%d %d”, &a, &b); myswap(a,b); // As a contrast , Swap two integers directly , Obviously not. printf(“ The result of calling the swap function is :%d and %d\n”, a, b); return 0; } #include<stdio.h> void myswap(int *p1, int *p2) { int t; t=*p1; *p1=*p2; *p2=t; } int main() { int a, b; printf(“ Please enter two integers to be exchanged :”); scanf(“%d %d”, &a, &b); myswap(&a,&b); // Exchange two addresses of integers printf(“ The result of calling the swap function is :%d and %d\n”, a, b); return 0; } #include<stdio.h> void myswap(int &x, int &y) { int t; t=x; x=y; y=t; } int main() { int a, b; printf(“ Please enter two integers to be exchanged :”); scanf(“%d %d”, &a, &b); myswap(a,b); // Directly in variables a and b Exchange as arguments printf(“ The result of calling the swap function is :%d and %d\n”, a, b); return 0; } The running result of the first : Input 2 3, Output 2 3 The running result of the second : Input 2 3, Output 3 2 The running result of the third : Input 2 3, Output 3 2
analysis : In the first program , The reason why the value transfer is unsuccessful is that the value of the formal parameter is changed , Do not change the value on the argument . In the second program , The reason for the success of address transmission is that the original address is changed by using the pointer , So the arguments are exchanged .
In the third program , Reference is to directly change two argument variables a,b Value , So I switched .
The following will explain in detail about value transmission through examples , Pointer passing , reference
1) Value passed :
A formal parameter is a copy of an argument , Changing the value of a parameter does not affect the value of the external argument . From the perspective of the called function , Value passing is unidirectional ( Actual parameters -> Shape parameter ), The value of the parameter can only be passed in ,
It can't come out . When a function needs to modify its parameters , And don't want the change to affect the caller , Use value transfer .
2) Pointer passing :
A parameter is a pointer to the address of an argument , When pointing to a parameter , It is equivalent to the operation of the argument itself
3) reference :
The formal parameter is equivalent to the actual parameter “ Alias ”, The operation of formal parameters is actually the operation of actual parameters , In the process of reference passing , The formal parameters of the called function are also used as local variables to open up memory space in the stack , But 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 parameter is treated as indirect addressing , That is, through the address stored in the stack to access the arguments in the main function . Because of that , Any operation of the called function on the formal parameter will affect the real parameter variable in the main function .
The following code explains this in detail ( From the actual parameters , The angle at which formal parameters store addresses in memory It explains the essence of the problem , Easy to understand )
1 #include<iostream>
2 using namespace std;
3 // Value passed
4 void change1(int n){
5 cout<<" Value passed -- Function operation address "<<&n<<endl; // The copy address is displayed instead of the source address
6 n++;
7 }
8
9 // reference
10 void change2(int & n){
11 cout<<" reference -- Function operation address "<<&n<<endl;
12 n++;
13 }
14 // Pointer passing
15 void change3(int *n){
16 cout<<" Pointer passing -- Function operation address "<<n<<endl;
17 *n=*n+1;
18 }
19 int main(){
20 int n=10;
21 cout<<" The address of the argument "<<&n<<endl;
22 change1(n);
23 cout<<"after change1() n="<<n<<endl;
24 change2(n);
25 cout<<"after change2() n="<<n<<endl;
26 change3(&n);
27 cout<<"after change3() n="<<n<<endl;
28 return true;
29 }
The operation results are as follows ,( Different machines may differ )
It can be seen that , The address of the argument is 0x22ff44
When using value transfer , The address of the function operation is 0x22ff20 It's not the argument itself , So operating on it does not change the value of the argument
- Look at reference passing , The operation address is the argument address , Just an alias equivalent to an argument , The operation on it is the operation on arguments
- Next is pointer passing , You can also find that the operation address is the argument address
that , Is there any difference between reference passing and pointer passing ?
The rules quoted : References must be initialized at the same time as they are created ( Pointers can be initialized at any time ).
- Can not have NULL quote , The reference must be associated with a legal storage unit ( The pointer can be NULL).
- Once the reference is initialized , You can't change the citation relationship ( The pointer can change the object at any time ).
The essence of pointer passing :
Pointer passing parameters is essentially a way of passing values , It's passing an address value . In the process of value passing , The formal parameters of the modulated function are treated as local variables of the modulated function , That is, memory space is opened up in the stack to store the value of the actual parameter put in by the main function , So it becomes a copy of the argument . The characteristic of value passing is that the function to be called has the function to the formal parameter
Any operation is done as a local variable , Does not affect the value of the argument variable of the main function .( This means that the address value of the argument pointer itself will not change ) If you don't understand, you can skip this paragraph
Pointer passing and reference passing generally apply to :
Modify the parameters inside the function and want the changes to affect the caller . Contrast pointer / Reference passing can be changed by formal parameters “ Pass to ” Actual parameters ( In fact, it is directly modified in the memory of the argument , Unlike value passing, you copy the value of an argument to another memory address to modify it ).
Another usage is : When a function actually needs to return multiple values , When only one value can be returned explicitly , You can use another variable that needs to be returned as a pointer / Reference passed to function , So after modifying inside the function and returning , The caller can get the modified variable , It's also equivalent to passing an implicit return value .
The following is what I think is a good article about pointers and citations , You can refer to , Original source address :http://xinklabi.iteye.com/blog/653643
conceptually . A pointer is essentially a variable that stores the address of a variable , 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 .
And reference is an alias , It's not logically independent , Its existence is dependent , So references have to be initialized at the beginning , And the object it refers to cannot be changed throughout its life cycle ( Can only be attached to the same variable from beginning to end ).
stay C++ in , Pointers and references are often used in function parameter passing , However , There is a fundamental difference between pointer passing parameters and reference passing parameters :
Pointer passing parameters is essentially a way of passing values , It's passing an address value . In the process of value passing , The formal parameters of the modulated function are treated as local variables of the modulated function , That is, memory space is opened up in the stack to store the value of the actual parameter put in by the main function , So it becomes a copy of the argument . The characteristic of value transfer is that any operation of the called function on the formal parameters is carried out as a local variable , Does not affect the value of the argument variable of the main function .( This means that the address value of the argument pointer itself will not change )
In the process of reference passing , The formal parameters of the called function are also used as local variables to open up memory space in the stack , But 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 parameter is treated as indirect addressing , That is, through the address stored in the stack to access the arguments in the main function . Because of that , Any operation of the called function on the formal parameter will affect the real parameter variable in the main function .
Reference passing and pointer passing are different , Although they are all local variables in the called function stack space , However, any processing of the reference parameter will operate to the related variables in the calling function through an indirect addressing method . And for the parameters passed by the pointer , If you change the pointer address in the called function , It will not affect the related variables of the main function . If you want to change the related variables in the main function by passing pointer parameters , Then you have to use a pointer to the pointer , Or pointer reference .
In order to further deepen the difference between pointer and reference , Let me explain the differences between them from the perspective of compilation :
The program adds pointers and references to the symbol table at compile time , The symbol table records the variable name and the address corresponding to the variable . The corresponding address value of the pointer variable on the symbol table is the address value of the pointer variable , The corresponding address value of the reference in the symbol table is the address value of the reference object . After the symbol table is generated, it will not be changed , So a pointer can change the object it points to ( The value in the pointer variable can be changed ), Reference objects cannot be modified .
Last , Summarize the similarities and differences between pointers and references :
1) The same thing :
- It's all about the concept of address ;
Pointer to a block of memory , Its content is the address of the memory ; A reference is an alias for a block of memory .
2) Difference :
- A pointer is an entity , And the reference is just an alias ;
- References can only be initialized once at definition time , After that, it's immutable ; Pointer variable ; quote “ be faithful to one 's husband unto death ”, The pointer can “ wish to change one 's work the moment one sees sth. different ”;
- There is no quotation const, The pointer has const,const The pointer of is immutable ;( Specifically, there is no int& const a This form , and const int& a Yes, there is Of , The former refers to the reference itself, that is, the alias cannot be changed , Of course , So you don't need this form , The latter means that the value referred to by the reference cannot be changed )
- Reference cannot be empty , The pointer can be empty ;
- “sizeof quote ” What you get is the variable you're pointing to ( object ) Size , and “sizeof The pointer ” What we get is the size of the pointer itself ;
- Autoincrement of pointers and references (++) The meaning of operation is different ;
- References are type safe , And the pointer is not ( There are more references than pointers, type checking )
One 、 Concept of reference
Reference introduces a synonym for an object . Defining a reference is represented in a way similar to defining a pointer , Just use & Instead of *.
for example : Point pt1(10,10);
Point &pt2=pt1; Defined pt2 by pt1 References to . By this definition ,pt1 and pt2 Represents the same object .
It should be emphasized that references do not produce copies of objects , Just synonyms for objects . therefore , When the following statement is executed :
pt1.offset(2,2);
pt1 and pt2 All have (12,12) Value .
References must be initialized as soon as they are defined , Because it must be synonymous with something . You cannot define a reference before
Initialize it . For example, the following statement is illegal :
Point &pt3;
pt3=pt1;
So since quotation is only a synonym of something , What's the use of it ?
The two main uses of citations are discussed below : As function parameters and return lvalues from functions .
Two 、 reference parameter
1、 Passing variable parameters
Conventional c in , When a function is called, parameters are passed by value , This means that the parameters of the function do not have the ability to return values .
So in the traditional c in , If you want the function's parameters to have the ability to return values , It is often achieved through pointers . such as , Realization
The values of two integer variables are exchanged c The procedure is as follows :
One 、 Concept of reference
Reference introduces a synonym for an object . Defining a reference is represented in a way similar to defining a pointer , Just use & Instead of *.
for example : Point pt1(10,10);
Point &pt2=pt1; Defined pt2 by pt1 References to . By this definition ,pt1 and pt2 Represents the same object .
It should be emphasized that references do not produce copies of objects , Just synonyms for objects . therefore , When the following statement is executed :
pt1.offset(2,2);
pt1 and pt2 All have (12,12) Value .
References must be initialized as soon as they are defined , Because it must be synonymous with something . You cannot define a reference before
Initialize it . For example, the following statement is illegal :
Point &pt3;
pt3=pt1;
So since quotation is only a synonym of something , What's the use of it ?
The two main uses of citations are discussed below : As function parameters and return lvalues from functions .
Two 、 reference parameter
1、 Passing variable parameters
Conventional c in , When a function is called, parameters are passed by value , This means that the parameters of the function do not have the ability to return values .
So in the traditional c in , If you want the function's parameters to have the ability to return values , It is often achieved through pointers . such as , Realization
The values of two integer variables are exchanged c The procedure is as follows :
void swapint(int *a,int *b)
{
int temp;
temp=*a;
a=*b;
*b=temp;
}
After using the reference mechanism , Of the above procedure c++ Version is :
void swapint(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
To call this function c++ Method is :swapint(x,y); c++ Automatic handle x,y The address of is passed as a parameter to swapint function .
2、 Passing large objects to functions
When a large object is passed to a function , Using reference parameters can improve the efficiency of parameter transfer , Because references do not produce objects
copy , That is, when parameters are passed , Objects do not need to be copied . The following example defines a class of finite integer sets :
const maxCard=100;
Class Set
{
int elems[maxCard]; // Elements in sets and ,maxCard Represents the maximum number of elements in the set .
int card; // The number of elements in the collection .
public:
Set () {card=0;} // Constructors
friend Set operator * (Set ,Set ) ; // Overloaded operation symbols *, Used to calculate the intersection of sets Use the object as the value transfer parameter
// friend Set operator * (Set & ,Set & ) Overloaded operation symbols *, Used to calculate the intersection of sets Use 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;
}
Because overloaded operators cannot operate on pointers alone , We must declare the operand as Set Type, not Set * .
Each use * When doing intersection operation , The whole set is copied , It's inefficient . We can use quotation 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、 ... and 、 Reference return value
If a function returns a reference , Then the function call can also be assigned . Here's a function , It takes two reference parameters and returns a reference to a double :
double &max(double &d1,double &d2)
{
return d1>d2?d1:d2;
}
because max() Function returns a reference to a double , So we can use it max() To add... To the larger double 1:
max(x,y)+=1.0;
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/148435.html Link to the original text :https://javaforall.cn
边栏推荐
- QQmlApplicationEngine
- Leetcode 面试题 16.11. 跳水板
- 微信核酸检测预约小程序系统毕业设计毕设(2)小程序功能
- 快速排序基本思路(通俗易懂+例子)「建议收藏」
- 微信核酸检测预约小程序系统毕业设计毕设(4)开题报告
- Uncover the whole link communication process of dewu customer service im
- Picking up the camera is the best artistic healing
- Wechat nucleic acid detection appointment applet system graduation design completion (4) opening report
- 国金证券是国企吗?在国金证券开户资金安全吗?
- Web实时通信技术之Websocket
猜你喜欢
Chrome 正式支持 MathML,默认在 Chromium Dev 105 中启用
Qt Official examples: Qt Quick Controls - Gallery
A good programmer is worth five ordinary programmers!
Leetcode interview question 17.01 Addition without plus sign
微信小程序视频分享平台系统毕业设计毕设(4)开题报告
Leetcode 面试题 16.11. 跳水板
Wechat nucleic acid detection appointment applet system graduation design completion (4) opening report
拿起相机,便是最好的艺术疗愈
Ue4 dessine un cercle avec une ligne de contour
呆错图床系统源码图片CDN加速与破J防盗链功能
随机推荐
What is cloud primordial? This time, I can finally understand!
Nvidia 显卡 Failed to initialize NVML Driver/library version mismatch 错误解决方案
昨天阿里学长写了一个责任链模式,竟然出现了无数个bug
UE4 用spline画正圆
Architecture design - ID generator "suggestions collection"
在支付宝账户上买基金安全吗
Deep neural network Summary
IPtable port redirection masquerade[easy to understand]
如何设置VSCode删除整行快捷键?
300+篇文献!一文详解基于Transformer的多模态学习最新进展
Unity learning shader notes [82] black and white processing of enhanced single channel color rendering
Three methods of MySQL backup
Unity学习shader笔记[八十二]增强单通道颜色渲染的黑白处理
Chrome 正式支持 MathML,默认在 Chromium Dev 105 中启用
Night God simulator +fiddler packet capture test app
阿里三面被面试官狂问Redis,简历上再也不敢写'精通'了
UE4 用spline畫正圓
Paddlepaddle 28 build an automatic coder based on convolution
科技公司不同人对Bug的反应 | 每日趣闻
Export Excel files using npoi