c++ - Difference between pre and post decrement in recursive function argument -


i have following sample code used pre-decrement

void function(int c) {   if(c == 0)   {      return;   }   else   {     cout << "dp" << c << endl;     function(--c);     cout << c << endl;     return;   } } 

this function give output input 4 :

 dp3  dp2  dp1  dp0  0  1  2  3 

but when use post decrement

void function(int c) {   if(c == 0)   {     return;   }   else   {     cout << "dp" << c << endl;     function(c--);     cout << c << endl;     return;   } } 

output goes in infinite loop dp4

can explain me in detail why happens ?

this happens because function(c--) called same value of c , when finishes c decremented. recursively called, hence called same value no chance of return , hit stack overflow error.

assume this, int x = 1, y = 0; y = x++ result y == 1 , x == 2. if y = ++x , bot x , y 2.


Comments

Popular posts from this blog

c# - Retrieve google contact -

javascript - How to insert selected radio button value into table cell -