c - 第二个 printf ("%d\n", n);被叫?

标签 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();
 }

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

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

从我脑海中可以追踪到的,both() 被 main 调用,并且在第二个 printf() 可以被访问之前它一直被调用,直到整个代码结束,因为当输入无效值(只是 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

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

关于c - 第二个 printf ("%d\n", n);被叫?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54977917/

相关文章:

html - 能用C输出图片吗?

c - 我应该如何编译这个C代码?

c++ - 用于 C++ 的快速、庞大且可扩展的几何库

c++ - 如何将函数作为参数从 C 传递给 C++,然后返回给 C

c - 获取 UDP 套接字的随机端口

c - 将整数值输入到 C 中的数组中

c 指向指针内存分配的指针

c - 如果输出到终端,则在 C 中检测

c - 编写处理任何类型数组的函数

c - 卡在逻辑门 C 程序上。 (C 新手)