c++ - 堆栈调用 : why is the cursor jumping to a specific position of the recursive function

标签 c++ recursion

问题描述

我正在尝试解决以下问题:

Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses. EXAMPLE: input: 3 (e.g., 3 pairs of parentheses) output: ()()(), ()(()), (())(), ((()))


当我研究基本情况时,当调用从堆栈中弹出时,它总是跳转到代码的后续部分;

 cout <<"==============> RESTART HERE " << endl;

问题

为什么在return 语句 之后光标没有返回到函数的开头。为什么从cout <<"==============> RESTART HERE " << endl;重新启动

例如,在这段代码中,它总是从头开始:

void HelloWorld(int count)
{
    if(count<1) return;
    if(count<0) return;
    cout << " Hello World!" << endl;
    HelloWorld(count - 1);
}

下图是第一次运行的调用栈。

enter image description here


源代码

# include<stdio.h>
#include <iostream>

using namespace std;

# define MAX_SIZE 100

void _printParenthesis(int pos, int n, int open, int close);

/* Wrapper over _printParenthesis()*/
void printParenthesis(int n)
{
  if(n > 0)
     _printParenthesis(0, n, 0, 0);
  return;
}

void _printParenthesis(int pos, int n, int open, int close)
{
  static char str[MAX_SIZE];
  if(close == n)
  {
    cout <<" open " << open <<" close " << close <<" " << pos<< endl;
    cout << str << endl;
    return;
  }
  else
  {
    if(close < open) {
        str[pos] = '}';
        cout <<" B open " << open <<" close " << close <<" " << pos<< " }" << endl;
        _printParenthesis(pos+1, n, open, close+1);

    }
    cout <<"==============> RESTART HERE " << endl;
    if(open < n) {
       str[pos] = '{';
        cout <<" A open " << open <<" close " << close <<" " <<pos << " {"  << endl;
        _printParenthesis(pos+1, n, open+1, close);

    }
  }
}

/* driver program to test above functions */
int main()
{
  int n = 3;
  printParenthesis(n);
  getchar();
  return 0;
}

最佳答案

您可能正在优化代码上运行调试器。这样做没有错,但优化器可能重新排序了代码。如果乱序执行困扰您,请在使用调试器时关闭优化器。

关于c++ - 堆栈调用 : why is the cursor jumping to a specific position of the recursive function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41666417/

相关文章:

c++ - x 秒后终止正在运行的线程的最佳方法是什么?

c++ - 检查框内是否有 3D 点

javascript - 向后遍历不可计算的嵌套数组,节点遍历 - Javascript?

c++ - 为什么此递归没有得到其基本情况?

haskell - 在 Haskell 函数定义的参数符号之间使用冒号有什么作用?

arrays - 合并哈希和键同时获得旧值和新值

c++ - 为什么我不能获取存储单元 n 中的内容?

c++ - 将 3D 数组作为结构成员存储在堆上

c++ - 在cpp中围绕原点旋转一个点?

recursion - 是什么让数据结构递归?