3

So I am trying to figure out how to completely break out of a recursive function in C++.

In the example I have the two-dimensional array that holds the necessary information which is correct. In the event of no recursion everything works as expected - the part that returns time[start] breaks out of the function.

In the case of recursion, return breaks out of the current recursion, but the function itself continues to go on iterating every next i from the for loop. I would like the function to stop at this point.

Is there a way to break out of the function all together?

int findConn(int **computers, int *time, int *connections, int cnt, int k, int start){
    for (int i=0; i<cnt; i++){
        if ((computers[k][i]!=0)&&(i!=start)&&(i!=k)){
            if(computers[start][i]!=0){
                time[start]++;
                return time[start];
            } else {
                time[start]++;
                k=i;
                findConn(computers, time, connections, cnt, k, start);
            }
        }
    }
    return 0;
}
LordOnion
  • 31
  • 4

1 Answers1

-1
    const int nBreakAll = -1;
    int findConn(int **computers, int *time, int *connections, int cnt, int k, int start){
        for (int i=0; i<cnt; i++){
            ...
            if(break condition)
                 return nBreakAll;
            ....
            if ( nBreakAll  == findConn(...) )
            {
                 return nBreakAll; //this handles the break of recursive loop
            }
            //continues here
            ....

        }
        return 0;
    }
jimmy
  • 1
  • 1
  • 2
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Vishal Chhodwani May 24 '18 at 12:22