[英]I'm confused by recursion in my “convert decimal to binary string” code
void print_binary(int number)
{
if (number){
print_binary(number/2);
putc((number % 2) ? '1' : '0', stdout);
}
}
int main(void) {
print_binary(8);
}
上面的代码返回“1000”。 但是当我将print_binary()
中的两行反转并这样写时:
void print_binary(int number)
{
if (number){
putc((number % 2) ? '1' : '0', stdout);
print_binary(number/2);
}
}
字符串是“0001”。
我不明白为什么会这样。 任何解释表示赞赏。 谢谢
在第一个代码示例中,执行如下:
print_binary(8/2)
print_binary(4/2)
print_binary(2/2)
print_binary(1/2) // 1/2 = 0 => this is terminating condition of recursion
// stack windup from here
putc((1 % 2) ? '1' : '0', stdout); --> output 1
putc((2 % 2) ? '1' : '0', stdout); --> output 0
putc((4 % 2) ? '1' : '0', stdout); --> output 0
putc((8 % 2) ? '1' : '0', stdout); --> output 0
因此, output 是1000
。
在第二个代码示例中,执行如下:
putc((8 % 2) ? '1' : '0', stdout); --> output 0
print_binary(8/2)
putc((4 % 2) ? '1' : '0', stdout); --> output 0
print_binary(4/2)
putc((2 % 2) ? '1' : '0', stdout); --> output 0
print_binary(2/2)
putc((1 % 2) ? '1' : '0', stdout); --> output 1
print_binary(1/2) // 1/2 = 0 => this is terminating condition of recursion
// stack windup from here and nothing to do after last
// recursive call
因此, output 是0001
。
当您调用 function 时,程序将当前地址放入堆栈 memory 堆栈指针指向的位置,以便在执行结束时返回并跳转到函数的地址。 堆栈是一种 LIFO(后进先出)结构,因此当您调用 function 时,程序会完成 function 中的指令,而不是返回原来的位置。 这就是为什么要更改订单。
void print_binary(int number)
{
if (number){
putc((number % 2) ? '1' : '0', stdout); // 1st instruction
print_binary(number/2); // 2nd instruction
}
}
该程序的工作原理如下:
所以 output 是 0001
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.