根据我对 C 的了解,在下面的代码中,应该执行函数 fact
中的第一个 return 语句。而是执行函数中的最后一个 return 语句。代码如何在这里工作?为什么函数 fact
中的第一个 return 语句没有执行?
一个数的阶乘:
#include <stdio.h>
int a = 2, count = 1, fact0 = 1;
int fact(int n) {
if (n == count) {
return fact0;//Only this return statement should be executed
}
fact0 = fact0 * a;
a++;
count++;
fact(n);
return 1;//But this return statement is executed , Why?
}
int main() {
int n;
setbuf(stdout, NULL);
printf("Enter the factorial number\n");
scanf("%d", &n);
printf("The factorial of the number is %d", fact(n));
return 0;
}
输出是:
Enter the factorial number
4
The factorial of the number is 1
最佳答案
你有一堆嵌套的函数调用。最内层从您期望的位置返回,其他从其他 return
语句返回。
// 1st call, in main
fact(4); // calls fact(4) with count == 2
fact(4); // calls fact(4) with count == 3
fact(4); // calls fact(4) with count == 4
return fact0; // as expected
return 1;
return 1;
关于c - 如果有多个return语句,那么C中的return语句是如何执行的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53131615/