![](https://i-blog.csdnimg.cn/blog_migrate/bc78e6d2772b629eb2e45d9fb3c02308.png)
c语言 引用调用
Now armed with the knowledge of pointers lets move our quest to learn C programming one step forward. Today I will tell you about the second advance feature of functions i.e. call by value and call by reference in C. Knowingly or unknowingly we have used the call by value feature in many programs till now. So it will be easy to understand the logic behind it. On the other side call by reference is used with pointers.
Call by Value in C
In previous tutorials I told you about the actual and formal arguments (parameters). In this method, whenever we make changes in formal arguments then it doesn’t change the value in actual arguments. As its name suggests, call by value feature means calling the function and passing some values in it. The values of actual arguments are copied into formal arguments. We have done it so many times till now. Lets take a fresh example to understand it quickly.
Output
Explanation
- The program code is almost self-explanatory. First I have printed the value of variable a before calling of function and then I have passed one argument in the function fun().
- The value of variable a of main() is copied into variable a of function fun().
- Now I have changed the value of variable a by adding 5 in it. After that I have printed the variable a in function fun().
- At last the value of variable a is again printed in main(). You can observe in output that the change that was done in variable a in function fun() is not affected the value of variable a in main().
Call by Reference in C
As I told earlier while applying call by value feature of functions we cannot change the values in actual arguments by changing the values in formal arguments. Many times we stick in a condition when we need to change the values of actual arguments in any other function. In those cases we use call by reference method.
In this method we will send the address of variables to the function. Any changes in formal arguments causes change in actual arguments. Lets build a simple program to understand this topic.
Output
Explanation
- In the beginning I have declared the function fun() with its argument as integer pointer.
- In the function call I have passed the address of variable a instead of passing its value.
- Now I have the address in pointer variable a of function fun().
- Then I have done some changes in the pointer variable and printed its value. Finally the variable a is again printed in main()
- You can see in the output that the change done in the pointer variable a of function fun() causes change in variable a of main().
You may face difficulty in understanding the concept of call by reference. You can ask your queries by commenting below.
翻译自: https://www.thecrazyprogrammer.com/2015/01/call-by-value-and-call-by-reference-in-c.html
c语言 引用调用