[英]Please, can you help me with this recursive function?
#include <stdio.h>
int fun (int x)
{
if (x<1)
return(1);
else
printf("%d %d \n", x, fun(x-1));
}
int main()
{ int x,y;
x = 5;
y = fun(x);
printf("\n x = %d f(x) = %d \n", x, y);
return 0;
}
This program contains a recursive function that count some numbers. 该程序包含一个计算一些数字的递归函数。 There is something in the output I cannot understand.
输出中有些东西我听不懂。 There is a screenshot of the output at the following link:
以下链接提供了输出的屏幕截图:
https://onedrive.live.com/redir?resid=BE4862D617298D2C!886&authkey=!AA03bF8dQ5W4S9Y&v=3&ithint=photo%2cpng https://onedrive.live.com/redir?resid=BE4862D617298D2C!886&authkey=!AA03bF8dQ5W4S9Y&v=3&ithint=photo%2cpng
Why the right column (red circuled) is as shown? 为什么显示右栏(红色圆圈)? I thought that this column will be all ones instead of that.
我认为本专栏将全部代替。
Because the function fun
didn't have a return value when x >= 1. 因为当x> = 1时,
fun
函数没有返回值。
And the 5 is the return value of printf("%d %d \\n", x, fun(x-1));
而5是
printf("%d %d \\n", x, fun(x-1));
的返回值printf("%d %d \\n", x, fun(x-1));
because it has output 5 characters. 因为它已输出5个字符。
You are not returning anything if x>=1
, causing undefined behaviour when the execution reaches the end of the function. 如果
x>=1
,则不返回任何内容,当执行到达函数末尾时会导致未定义的行为。 That means the value could be anything, you got 5 by chance. 这意味着该值可以是任何值,您偶然得到5。
6.9.1.
6.9.1。 p12:
第12页:
If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
如果到达终止函数的},并且调用者使用了函数调用的值,则该行为未定义。
The return value is used in your example. 在您的示例中使用了返回值。
int fun(int x)
{
if (x<1)
return(1);
else
printf("%d %d \n", x, fun(x-1));
return x ;//just return something
}
You probably want to return something relevant to what you function does. 您可能想返回与您的功能有关的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.