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

问题描述 投票:1回答:2
// 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
2个回答
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

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


1
投票

在这种情况下,你头脑中的想法绝对正确。由于在同一个thread中调用“both”函数,后续行的执行将被保持,直到新调用的“both”函数的执行完成。在计算理论中,这被称为recursion,并且停止调用“both”(递归)函数的条件称为base case

所以调用的总结看起来像:i-input(value),p-printf(value),b-both(),rOi-来自两者的代码的其余部分用于输入(值) I(1) - > P(1) - > B() - > I(2) - > P(2) - > B() - > I(3) - > P(3) - > B() - > i(4) - > p(4) - > b() - > i(5) - > p(5) - > b() - > i(无效,如果条件失败) - > rOi(5) - > ROI(4) - > ROI(3) - > ROI(2) - > ROI(1)

© www.soinside.com 2019 - 2024. All rights reserved.