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

huangapple go评论71阅读模式
英文:

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

问题

这个递归函数 'int f(int n)' 在 'n == 1' 时才会返回值。如果我们将 **n = 2,3**,那么 **y = 2**。当 **n = 4,5** 时,**y = 3**,当 **n = 6,7,8** 时,**y = 4** 以此类推。这里,*变量 x 是静态的*。以下是代码:

```c
#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);
    }

请帮我理解如何赋值给 y 或者 f() 如何返回这样的值。谢谢。

我期望的结果是 2,3,4,5,6,7。我能够通过实现一些其他的东西来得到这些值,但这并不是我想要理解的。我想了解的是当 n 为 2,3 时,f() 如何得到值而没有 return 语句?


<details>
<summary>英文:</summary>

This recursive function &#39;int f(int n)&#39; should not return anything except when &#39;n == 1&#39;. If we put
**n = 2,3** then **y = 2**. When **n = 4,5** then **y = 3**, when **n = 6,7,8** then **y = 4 **and so on. Here, *variable x is static.* Below is the code:

#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.
Thank you.



I was expecting 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. How f() is returning a value without the return statement?

</details>


# 答案1
**得分**: 1

函数 `f` 不在所有的代码路径上返回一个值。这意味着未定义行为。它可能返回任何值,或者 `y` 可能保持未初始化状态。

<details>
<summary>英文:</summary>

The function `f` doesn&#39;t return a value on all code paths.  This means undefined behavior.  It may return anything, or `y` may remain uninitialized.

</details>



huangapple
  • 本文由 发表于 2023年1月9日 16:47:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054877.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定