[英]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.