简体   繁体   English

无法理解 function 在没有返回语句但 C 语言中有 int 返回类型时如何返回特定值

[英]Not able to understand how a function is returning a specific value when there is no return statement but there is an int return type in C language

This recursive function 'int f(int n)' should not return anything except when 'n == 1'.此递归 function 'int f(int n)' 不应返回任何内容,除非 'n == 1'。 If we put n = 2,3 then y = 2 .如果我们把n = 2,3那么y = 2 When n = 4,5 then y = 3 , when n = 6,7,8 then **y = 4 **and so on.n = 4,5那么y = 3 ,当n = 6,7,8那么 **y = 4 ** 等等。 Here, variable x is static. Below is the code:这里,变量 x 是 static。下面是代码:

#include <stdio.h>
int f(int n){
        static int x=1; 
        int i;
        if(n==1){
            return 1;
        }
        else {
            for(i = 1; i<=2; i++){
                x = x + f(n-1);
                printf("%d\n",x);
            }
        }
}
int main() {
    int n = 3;
    int y =f(n);
    printf("y %d",y);
    }

Kindly help me understand how the value of y is assigned or how f() is returning such values.请帮助我了解如何分配 y 的值或 f() 如何返回此类值。 Thank you.谢谢你。

I was expecting 2,3,4,5,6,7.我期待 2、3、4、5、6、7。 I am able to get those values implementing some other stuff but that is not what I want to understand.我能够让这些价值观实现一些其他的东西,但这不是我想要理解的。 I want to understand the f() is 2, when n is 2,3.我想了解 f() 是 2,当 n 是 2,3 时。 How f() is returning a value without the return statement? f() 如何在没有 return 语句的情况下返回值?

The function f doesn't return a value on all code paths. function f不会在所有代码路径上返回值。 This means undefined behavior.这意味着未定义的行为。 It may return anything, or y may remain uninitialized.它可能返回任何东西,或者y可能保持未初始化状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM