C 语言中函数调用的类型
原文:https://www.studytonight.com/c/types-of-function-calls.php
函数都是用名字来称呼的,我们都知道,那这个教程是为了什么呢?如果函数没有任何参数,那么要调用一个函数,你可以直接使用它的名字。但是对于带参数的函数,根据我们如何指定参数,我们可以用两种不同的方式调用函数,这两种方式是:
- 按值调用
- 引用调用
按值调用
通过值调用函数意味着,我们将存储或复制的参数值传递到函数的形式参数中。因此,原始值不变,只有函数内部的参数发生变化。
#include<stdio.h>
void calc(int x);
int main()
{
int x = 10;
calc(x);
// this will print the value of 'x'
printf("\nvalue of x in main is %d", x);
return 0;
}
void calc(int x)
{
// changing the value of 'x'
x = x + 10 ;
printf("value of x in calc function is %d ", x);
}
计算函数中 x 的值是 20,主函数中 x 的值是 10
在这种情况下,实际的变量 x
不变。这是因为我们是通过值传递参数的,因此x
的副本被传递给函数,函数在执行过程中会更新,当函数结束(超出范围)时,函数中复制的值会被破坏。因此main()
函数中的变量x
从未改变,因此仍然保持10
的值。
但是我们可以改变这个程序,让函数修改原来的x
变量,方法是让函数calc()
返回值,并将该值存储在 x 中。
#include<stdio.h>
int calc(int x);
int main()
{
int x = 10;
x = calc(x);
printf("value of x is %d", x);
return 0;
}
int calc(int x)
{
x = x + 10 ;
return x;
}
x 的值是 20
引用调用
在按引用调用中,我们将变量的地址(引用)作为参数传递给任何函数。当我们将任何变量的地址作为参数传递时,函数将可以访问我们的变量,因为它现在知道变量存储在哪里,因此可以轻松地更新它的值。
在这种情况下,形式参数可以作为一个引用或一个 指针 (不用担心指针,我们很快就会知道),在这两种情况下,它们都会改变原始变量的值。
#include<stdio.h>
void calc(int *p); // functin taking pointer as argument
int main()
{
int x = 10;
calc(&x); // passing address of 'x' as argument
printf("value of x is %d", x);
return(0);
}
void calc(int *p) //receiving the address in a reference pointer variable
{
/*
changing the value directly that is
stored at the address passed
*/
*p = *p + 10;
}
x 的值是 20
注意:如果你没有任何关于指针的先验知识,一定要先学习指针。或者,一旦你了解了指针,就复习一下这个话题,然后再回来修改。