Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion and pre-decrement operator

I have this function:

void m(int n)
{
    if(n > 0)
      m(--n);
      cout << n << " "; //for n = 5 --> output is: 0 0 1 2 3 4
}

I have a problem with understanding how it works. For example:

n(input) = 5

output: 0 0 1 2 3 4

My question is: Why does it show zero twice?

When I add brackets like this:

void m(int n)
{
    if(n > 0)
    {
        m(--n);
        cout << n << " "; // now, it shows 0 1 2 3 4 (n = 5)
    }
}

So, what brackets cause in this code, that "0" exists only once?

And when I change pre-decrement (--n) to post-decrement (n--) it shows nothing. Why?

Could somebody help me to understand how it works?

like image 448
gryzek Avatar asked Dec 19 '22 15:12

gryzek


2 Answers

First thing to note is : in C++ if you don't put brackets after an if statement, only the next line will be in the statement.

Example :

if(x > 0)
   cout << 1;
   cout << 2;

Here cout << 2 will always be executed no matter the value of x

The correct way of writing this is

if(x > 0)
{
  cout << 1;
  cout << 2;
}

Same thing goes for else statements So this was for the brackets.

My wild guess for the post decrement is the following : if you do m(n--), the value passed will be 5, the value of n will only change after the function call and go out of scope (so it won't matter). So what will happen is an infinite number of m(5) calls and that's why nothing is appearing. (I'm not sure about that part so please tell me if wrong) !

Hope it helped !

like image 115
Daniel Avatar answered Dec 30 '22 22:12

Daniel


Looks like you confused with Python syntax, where scope of if is determined by indent. In C (and C++, C#, Java an many other languages) the scope is one statement (which ends with ;) unless you use curly brackets { and }. In the 1st variant of your code cout << n << ... will be always performed, regardless of value of n. In second variant it will be performed only if(n > 0)

like image 40
mvidelgauz Avatar answered Dec 30 '22 22:12

mvidelgauz