Hani Goc
Hani Goc

Reputation: 2441

Stack call: why is the cursor jumping to a specific position of the recursive function

Problem description

I am trying to solve the following problem:

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: ()()(), ()(()), (())(), ((()))


The moment I rearch the base case and when the calls are being popped from from stack, it is always jumping to following part of the code;

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

Question

Why isn't the cursor returning to the beginning of the function after the return statement. Why is it restarting from cout <<"==============> RESTART HERE " << endl;

In this code for instance it always restarts from the beginning:

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

The following picture shows the call stack for the first run.

enter image description here


Source code

# 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;
}

Upvotes: 0

Views: 46

Answers (1)

Max Lybbert
Max Lybbert

Reputation: 20039

You are probably running a debugger on optimized code. There's nothing wrong with doing that, but the optimizer may have reordered code. If the out-of-order execution bothers you, turn off the optimizer when you use the debugger.

Upvotes: 2

Related Questions