C语言中的函数调用(call)详解及实例
在C语言中,'call'(调用)是指程序中的一个函数调用另一个函数的过程。下面是几个例子,生动形象地详细解释了C语言中的'call'。
- 嵌套调用:
#include <stdio.h>
void fun1() {
printf("Hello ");
}
void fun2() {
printf("World");
}
void main() {
fun1();
fun2();
}
在上面的例子中,函数fun1()调用了函数fun2(),通过函数调用来实现了在输出中打印'Hello World'。
- 递归调用:
#include <stdio.h>
int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n-1);
}
void main() {
int num = 5;
int result = factorial(num);
printf("Factorial of %d is %d", num, result);
}
在上面的例子中,函数factorial()调用了自身,实现了计算阶乘的递归算法。通过函数的递归调用,可以简洁地解决问题。
- 函数指针调用:
#include <stdio.h>
void fun1() {
printf("Hello ");
}
void fun2() {
printf("World");
}
void main() {
void (*funPtr)() = NULL;
funPtr = &fun1;
(*funPtr)();
funPtr = &fun2;
(*funPtr)();
}
在上面的例子中,通过函数指针的调用,可以根据需要动态地选择要调用的函数。首先,将函数指针funPtr指向函数fun1,然后通过(*funPtr)()调用函数fun1;然后将函数指针funPtr指向函数fun2,通过(*funPtr)()调用函数fun2。
- 带参数的函数调用:
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
void main() {
int num1 = 5;
int num2 = 10;
int result = add(num1, num2);
printf("The sum of %d and %d is %d", num1, num2, result);
}
在上面的例子中,函数add()带有两个参数a和b,通过函数调用add(num1, num2)将实际参数num1和num2传递给形式参数a和b,并返回它们的和。
通过这些例子,我们可以更好地理解C语言中的函数调用('call')的概念和使用方式。
原文地址: https://www.cveoy.top/t/topic/bpTK 著作权归作者所有。请勿转载和采集!