forest.peterson
forest.peterson

Reputation: 763

recursion with or without return statement in terminating condition

Please explain how the return statement functions for a simple recursive parse of a trie

CASE A:

if (true) push &stack; //push path result onto a stack
else{
   if (terminating condition true) return;
   else {
      condition 1 recursion to next node
      condition 2 recursions to next node
      ...
      condition n recursion to next node
   }
   recursion to next path;
}

CASE B:

if (true) {
   push &stack; //push path result onto a stack
   return;
}else{
   if (terminating condition true) return;
   else{
      condition 1 recursion to next node
      condition 2 recursion to next node
      ...
      condition n recursion to next node
   }
   recursion to next path;
}

Case A is working fine for me. But, I don't understand what happens after the result is pushed to the stack. How does 'it' know to terminate those paths?

Upvotes: 0

Views: 2129

Answers (2)

jfly
jfly

Reputation: 7990

For a function of return type void, a return statement is not strictly necessary. If the end of such a function is reached without encountering a return statement, control is passed to the caller as if a return statement without an expression were encountered. In other words, an implicit return takes place upon completion of the final statement, and control automatically returns to the calling function. Anyway, you needn't paid for another line of code, it's good practice to add a return statement.
But note that for a function declared with a non-void return type, it's required. It works sometimes without the return statement, for example, this one: Confused about the function return value. But it's the result of an undefined behavior.

Upvotes: 1

forest.peterson
forest.peterson

Reputation: 763

Case A works because the results are pushed to the stack or vector, or whatever structure is used and then terminates that specific path. If there was a return, it initiates the parsing of the stack and steps back through the previous iterations. So, in case B, only one result would be found.

Upvotes: 0

Related Questions