c++ - 递归:输出指定文本的原因?

标签 c++ c++11 recursion

我有一个简单的 C++ 递归问题。在我问我的问题之前,我认为最好展示一下我的代码。

void message(int times)
{
  if (times > 0)
  {
    cout << "This is a recursive function" << endl;
    message(times - 1);
  }
  cout << "message returning with " << times << " in times << endl;
}

设整型变量times设为5。 这是函数的输出

This is a recursive function
This is a recursive function
This is a recursive function
This is a recursive function
This is a recursive function
Message called with 0 in times
Message called with 1 in times
Message called with 2 in times
Message called with 3 in times
Message called with 4 in times
Message called with 5 in times

我明白为什么会输出“This is a recursive function”,但不明白为什么会输出“Message called with 0-5 in times”?谢谢

最佳答案

让我们看一下您的一小部分代码:

    message(times - 1);
}
cout << "message returning with " << times << " in times << endl;

您认为对 message() 的函数调用返回后会发生什么?您确实知道,当您调用一个函数时,一旦函数调用返回,调用者就会继续执行下一条语句,对吧?

这正是这里发生的事情。因此,当调用此代码时传递 5 作为 times 的值,这就是您最终看到的消息。

我敢肯定,无论您使用的是什么编译器,您都应该拥有一个配套的调试器工具,它可以让您在程序执行时逐步执行程序,一次一行。如果您花时间学习如何使用调试器,则可以将其用于您的程序,并亲眼看看每一行的执行方式和原因。

关于c++ - 递归:输出指定文本的原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36440176/

相关文章:

c++ - 两个类相互包含,下一段代码有什么问题?

c++ - 将多个 void* 复制到一个 vector 中

python - 理解二叉树的递归

java - 在java中检查有效的括号

c++ - 测试 boost::mpl::or_ 的计算结果是真还是假

c - 我的递归质数函数代码有一些错误

c++ - 在 Eclipse Kepler 上配置 C++11

c++ - Bazel 使用 OpenCV 3.3 依赖项构建

c++ - 是否可以在不锁定或提供 future 的情况下进行查找或创建?

c++ - 使用不依赖于方法模板参数的 enable_if