c - 如果有多个return语句,那么C中的return语句是如何执行的?

标签 c return

根据我对 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/

相关文章:

c - 将命令行参数和文本文件传递给程序

Javascript:多层条件,使用 "return false"停止以后的条件检查

C - 输入 2 个值,返回 2 个值到 MAIN。交换

javascript - 返回值异步方法

c - pipeline()-ing 程序会导致 EIO

c - c 中的结构数组 : giving all the strings same values (with the int it works well). 我该怎么办?

c++ - C/C++ 分配类似对象的数组数组

Python 线程返回值

c++ - 从 'int'类型的返回值到函数返回类型( vector )没有可行的转换

c - linux open调用返回EINVAL的可能原因