C 如何使用静态变量在递归函数中保持状态
我编写了以下玩具函数,以了解堆栈如何在递归函数调用时向下增长,然后在返回时展开:C 如何使用静态变量在递归函数中保持状态,c,recursion,C,Recursion,我编写了以下玩具函数,以了解堆栈如何在递归函数调用时向下增长,然后在返回时展开: void countdown(int n) { // trying to get initial address so the math is a bit simpler // on how much the stack grows down/up static intptr_t initial_address = (intptr_t) &n; if (n!=0) {
void countdown(int n) {
// trying to get initial address so the math is a bit simpler
// on how much the stack grows down/up
static intptr_t initial_address = (intptr_t) &n;
if (n!=0) {
printf("%d...at address: %p\n", n, &n);
countdown(n-1);
printf("%d...at address: %p\n", n, &n);
} else
printf("Liftoff!\n");
}
有没有一种方法可以在不向
倒计时
函数传递另一个参数的情况下执行类似操作?如果是,正确的方法是什么?一种方法是使用的地址或以前的地址的max
值,知道顶级函数调用将具有最高的堆栈地址。例如:
void countdown(int n) {
// will only be initialized once, and first value is throw-away, since
// the memory address is always going to be greater than zero
static intptr_t initial_address=0;
if (n!=0)
{
initial_address = initial_address > (intptr_t) &n ? initial_address : (intptr_t) &n;
// pushing upto the stack (will grow down...)
printf("%d...at address %p | offset: -%#zx\n", n, &n, initial_address - (intptr_t) &n);
countdown(n-1);
// stack unwinds after function starts returning
printf("%d...at address %p | offset: -%#zx\n", n, &n, initial_address - (intptr_t) &n); // pushing upto the stack (will grow down...)
}
else
printf("Liftoff!\n");
}
4…地址0x7ffe6944967c处偏移量:-03…地址0x7ffe6944965c处偏移量:-0x20
2…地址0x7ffe6944963c处偏移量:-0x40
1…地址为0x7ffe6944961c |偏移量:-0x60
发射
1…地址为0x7ffe6944961c |偏移量:-0x60
2…地址0x7ffe6944963c处偏移量:-0x40
3…地址0x7ffe6944965c处偏移量:-0x20
4…地址0x7ffe6944967c处|偏移量:-0
…或者您可以将另一个参数传递给倒计时函数,例如,指向状态结构的指针。@因此,对于上述内容,您只需添加另一个参数,例如
void count(int n,state*state){…}
?