Search code examples
c++recursiontrie

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?


Solution

  • 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.