2

I have following sample code where i 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 for input 4 as :

 DP3
 DP2
 DP1
 DP0
 0
 1
 2
 3

But when i 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 with DP4

Can you explain me in detail why this happens ?

user2864740
  • 60,010
  • 15
  • 145
  • 220
DigviJay Patil
  • 986
  • 14
  • 31
  • This happens because function(c--) will be called with the same value of c and when it finishes c will be decremented. But as it is recursively called, hence it will be called with same value with no chance of return and eventually you will hit stack overflow error. – Nipun Talukdar May 15 '15 at 05:22
  • Can you explain me how exactly pre and post works ? – DigviJay Patil May 15 '15 at 05:24
  • 1
    Assume this, int x = 1, y = 0; Now y = x++ will result y == 1 and x == 2. But if you do y = ++x , then bot x and y will be 2. – Nipun Talukdar May 15 '15 at 05:27
  • @NipunTalukdar Please add your explanation in answer so that i can upvote you – DigviJay Patil May 15 '15 at 05:30
  • 1
    When doing recursion it's better not to mutate the variable. eg. you can do `function(c-1)` instead. – Sylwester May 15 '15 at 09:51

3 Answers3

5

Because --c will return c-1,however c-- return c.So when you use function(c--) is equal to function(c);c = c-1;.c will never be 0.So the function won't stop. To know the difference between --x and x-- you can try the following code:

int x = 5,y=5;
cout<<x--<<endl;
cout<<--y<<endl;
cout<<x<<" "<<y<<endl;
icecity96
  • 1,177
  • 12
  • 26
5

This happens because function(c--) will be called with the same value of c and when it finishes c will be decremented. But as it is recursively called, hence it will be called with same value with no chance of return and eventually you will hit stack overflow error.

Assume this, int x = 1, y = 0; Now y = x++ will result y == 1 and x == 2. But if you do y = ++x , then bot x and y will be 2.

Nipun Talukdar
  • 4,975
  • 6
  • 30
  • 42
1

In case of post decrement value will be passed before decrement , always same value will be passed to function , it never come out .

function(c--), first it call function(c) later decrement c-- will happen .

Venkata Naidu M
  • 351
  • 1
  • 6