ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# C 编程中的按引用函数调用 > 原文: [https://beginnersbook.com/2014/01/c-function-call-by-reference-example/](https://beginnersbook.com/2014/01/c-function-call-by-reference-example/) 在我们讨论按引用函数调用之前,让我们理解我们将在解释这个时使用的术语: **实际参数**:函数调用中出现的参数。 **形式参数**:函数声明中出现的参数。 例如:我们有这样的函数声明: ```c int sum(int a, int b); ``` `a`和`b`参数是形式参数。 我们正在调用这样的函数: ```c int s = sum(10, 20); //Here 10 and 20 are actual parameters or int s = sum(n1, n2); //Here n1 and n2 are actual parameters ``` 在本指南中,我们将讨论按引用函数调用方法。如果要阅读按值调用方法,请参考本指南:[按值函数调用](https://beginnersbook.com/2014/01/c-function-call-by-value-example/)。 让我们回到原点。 **什么是按引用函数调用?** 当我们通过传递实际参数的地址来调用函数时,这种调用函数的方式称为按引用调用。在按引用调用时,对形式参数执行的操作会影响实际参数的值,因为对值执行的所有操作都存储在实际参数的地址中。它可能听起来很混乱,但下面的例子将清除你的怀疑。 ## 按引用函数调用的示例 让我们举一个简单的例子。阅读以下程序中的注释。 ```c #include <stdio.h> void increment(int *var) { /* Although we are performing the increment on variable * var, however the var is a pointer that holds the address * of variable num, which means the increment is actually done * on the address where value of num is stored. */ *var = *var+1; } int main() { int num=20; /* This way of calling the function is known as call by * reference. Instead of passing the variable num, we are * passing the address of variable num */ increment(&num); printf("Value of num is: %d", num); return 0; } ``` **输出:** ```c Value of num is: 21 ``` ## 示例 2:按引用函数调用 - 交换数字 这里我们使用按引用调用来交换数字。正如您所看到的,在调用`swapnum()`函数后,变量的值已经更改,因为交换发生在变量`num1`和`num2`的地址上。 ```c #include void swapnum ( int *var1, int *var2 ) { int tempnum ; tempnum = *var1 ; *var1 = *var2 ; *var2 = tempnum ; } int main( ) { int num1 = 35, num2 = 45 ; printf("Before swapping:"); printf("\nnum1 value is %d", num1); printf("\nnum2 value is %d", num2); /*calling swap function*/ swapnum( &num1, &num2 ); printf("\nAfter swapping:"); printf("\nnum1 value is %d", num1); printf("\nnum2 value is %d", num2); return 0; } ``` **输出:** ```c Before swapping: num1 value is 35 num2 value is 45 After swapping: num1 value is 45 num2 value is 35 ```