4

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?

gryzek
  • 537
  • 9
  • 25
  • It sounds like you may need to learn how to use a debugger to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming. Further reading: **[How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver Jun 24 '16 at 15:47
  • 1
    Fix indentation of first snippet to better understand. – Jarod42 Jun 24 '16 at 15:50

2 Answers2

7

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 !

Daniel
  • 1,172
  • 14
  • 31
  • 1
    You are right, `m(n--)` always call m(n) and after decrement `n` an nothing is appearing because `cout` will be made at the end of the recursion, but the recursion doesn't finish. – chema989 Jun 24 '16 at 16:02
  • So, it looks like: input: m(5) and m(n--) it menas: m(4) or it will be never "4" because it always go out of scope when input is "5"? – gryzek Jun 24 '16 at 16:10
4

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)

mvidelgauz
  • 2,176
  • 1
  • 16
  • 23