在一个递归函数的情况下获得的值 [英] Values obtained in case of a recursive function
问题描述
任何人都可以向我解释这个程序的输出背后的原因是 0 0 0 0 0
?
Can anyone explain to me the reason behind the output of this program to be 0 0 0 0 0
?
在这里,我们使用的是静态变量var
,其值因函数调用不会改变。 var的值
将 4,3,2,1
在递归调用。当 VAR
变为零的递归终止,到的printf
语句控制移动。
Here we are using a static variable var
whose values will not change due to function calls. The values of var
will be 4, 3, 2, 1
during the recursive calls. When var
becomes zero the recursion terminates and control moves on to the printf
statement.
为什么不输出 1,2,3,4
?
main(){
static int var=5;
if(--var)
main();
printf(" %d ",var);
}
此外,如果你使用,如果条件 VAR -
那么程序的输出将 -1 -1 -1 -1 -1 -1
?
推荐答案
在您的递归调用的printf()
执行时的main()
的回报。而由于 VAR
是静态变量
其值仍 0
(最后一个值= 0相同的所有函数调用)
In your recursion call printf()
executes when main()
returns. And because var
is a static variable
its value remain 0
(last value = 0 same for all function call)
请注意如果()
条件为假时, VAR
变成 0
(最后一个值,之后的main();叫你不要更改VAR - 通知图)。
Note if()
condition false when var
becomes 0
(last value, after main(); call you don't change var - notice diagram).
希望下面的图表会帮助你理解(阅读评论)
Hope following diagram will help you to understand (read comments):
main() <---------------+
{ |
static int var=5; | <----"Declared only one/first time with value 5"
if(--var) |
---- main(); ---------+ // called if var != 0
| // main called for var = 4, 3, 2, 1
|// recursion stooped
|// return with 0 value
|// now no operation applied on `var` so it remain 0
+--> printf(" %d ",var); // called when return ed
}
静态函数的剩余寿命,直至程序终止(所以没有价值损失),及适用范围是函数中。
Remainder life of static function is till program terminates (so values not loss), and Scope is within function.
静态自动变量的范围是相同的的
自动变量,即,它是本地其中是块
定义;然而,分配的存储成为永久的
程序的持续时间。静态变量可以在初始化其
声明;然而,的初始化必须是常量前pressions,
和初始化是在编译时内存仅完成一次
分配给静态变量*
The scope of static automatic variables is identical to that of automatic variables, i.e. it is local to the block in which it is defined; however, the storage allocated becomes permanent for the duration of the program. Static variables may be initialized in their declarations; however, the initializers must be constant expressions, and initialization is done only once at compile time when memory is allocated for the static variable*.
第二个问题:
此外,如果您使用 VAR -
那么你的输出将是 -1 -1 -1 -1 -1 -1
?
Again if you use
var--
then your output will be-1 -1 -1 -1 -1 -1
?
假设,如果你的状况会 VAR -
然后如果()
条件拳头检查真正
或假
之前递减 -
。 (因为前pression VAR -
, -
为后缀)结果。
而由于如果()
休息时 VAR
== 0
然后递归调用停止,函数返回值递减从 0
到 1
。而且由于后返回 VAR
并没有改变,因此输出为 1
所有。
Suppose if your condition will be var--
then if()
condition fist checks true
or false
before decrement --
. (because in expression var--
, --
is postfix).
And because if()
breaks when var
== 0
then recursive call stops and function returns with decremented value from 0
to -1
. And because after return var
doesn't change hence output is -1
for all.
这篇关于在一个递归函数的情况下获得的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!