c++ - Understanding recursion with small example -


hi have written small recursive method in cpp. trying understand recursion

void print(int n) {     if(n==6)         return;      print(++n);     cout<<n<<endl;     //output 6 5 4 3 2  } void print(int n) {     if(n==6)         return;      print(n+1);     cout<<n<<endl;     //output  5 4 3 2 1  }  void print(int n) {     if(n==6)         return;      print(n++);     cout<<n<<endl;     //programme crash  } 

could please explain me happening internally?

function calls placed on stack. think of stack of plates. time "print(x)" called in code, addition stack of plates. function removed stack when gets closing curly bracket or when hits return statement.

i assume you're calling print(0) on these functions. such print(0) first thing on stack. last function crashes because calls print(0) "forever" until fails have room more "plates." called infinite recursion , infinite recursion infinite due limitation of stack.

as other functions, well, "cout" statements called "after" functions removed off stack. each of these methods keeps placing new things on stack 1 exception, print(6) call. called base case , end of recursive process. because begins cascading removal of plates stacks allows cout statements occur (unlike infinitely recursive case).

to understand how these codes differ, must make sure understand difference between n++, ++n , n+1 well.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -