首页 > 解决方案 > 第二个 printf("%d\n", n); 怎么样?被叫?

问题描述

// both() reads integers and prints the numbers in their original order
//   and then in reverse order.
// effects: reads input, produces output
void both(void) {
  int n = read_int();

  if(n != READ_INT_FAIL) {
  printf("%d\n", n);
  both();
  printf("%d\n", n);
  } 
}

 int main(void) {
   both();
 }

因此,此代码读取整数并以原始顺序和相反的顺序打印数字。read_int() 是我的老师实现输入的一种方式。无论如何,假设输入是 1、2、3、4、5。预期的输出是 1、2、3、4、5、5、4、3、2、1(显​​然它是换行符而不是逗号,但我不想浪费垂直空间)。

所以我的问题是,这是如何工作的?

从我的脑海中可以追踪到,both()被main调用,并且在第二个printf()可以访问之前一直被调用,直到整个代码结束,因为当一个无效值时两者都不会被调用(只是5之后的任何随机字母)是输入。

这是如何运作的?

标签: c

解决方案


当递归停止时,程序并没有结束。both内部调用后将继续执行。所以这是一个快速的程序:

read_int = 1, print 1, call both() -> 1st recursion
read_int = 2, print 2, call both() -> 2nd recursion
read_int = 3, print 3, call both() -> 3rd recursion
read_int = 4, print 4, call both() -> 4th recursion
read_int = 5, print 5, call both() -> 5th recursion

read_int = 6, somehow the condition is true and the program continue at 5th recursion after the both() and print 5 again, so

5th recursion, print 5(second printf), end
4th recursion, print 4(second printf), end
3rd recursion, print 3(second printf), end
2nd recursion, print 2(second printf), end
1st recursion, print 1(second printf), end

希望这有助于代码的逻辑和执行。


推荐阅读