第二个printf(“%d \ n”,n)怎么样?被叫?

min*_*ing 1 c

// 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();
 }
Run Code Online (Sandbox Code Playgroud)

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

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

据我所知,both()它被main调用,并且在第二个printf()代码可以访问之前一直被调用,直到整个代码结束为止,因为当无效值(两个5之后的任意随机字母)都不会被调用时输入。

这是如何运作的?

小智 5

当递归停止时,程序不会结束。内部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
Run Code Online (Sandbox Code Playgroud)

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