0782 blessing
0782 blessing

Reputation: 21

how do i get numbers of recursive calls from this code?

using namespace std;
static int count = 0;
int f(int n, int& count)
{
    count++;
    if (n == 0 || n == 1) return n;
    else
        return f(n - 1, count) + f(n - 2, count);
}
int main()
{
    int n = 7;
    int count = 0;
    cout << f(n, count) << " " << count;
}

the output of count is 0 and i don't know why. my intend is to know the numbers of the recursive call

the thing before << is C out. if i connect them together i can't post the thing

Upvotes: 1

Views: 145

Answers (2)

jignatius
jignatius

Reputation: 6474

cout << f(n, count) << " " << count;

You would expect fn(n, count) to be evaluated first and then count, but if you're using a version of C++ earlier than C++17 then the order of evaluation is unspecified. << isn't a sequence point. The compiler is free to evaluate either count first or fn(n, count). Hence the output that you get, i.e. count is evaluated first.

What you could do is introduce a sequence point like this:

cout << f(n, count);  //semicolon is a sequence point
cout << " " << count;

and you should get the output you're expecting. Also there is no need for a static varaible at all as the count is passed by reference.

Upvotes: 1

Suryansh Singh
Suryansh Singh

Reputation: 9

In your code, you don't need to use the static int count=0 as you are passing the reference to the variable count declared in main, but still, it won't change the output. The following code works in gcc compiler. I feel corrected by a comment from another user that the problem might be with the C++ version.

#include <iostream>
using namespace std;
int f(int n, int& count)
{
    count++;
    if (n == 0 || n == 1) return n;
    else
        return f(n - 1, count) + f(n - 2, count);
}
int main()
{
    int n = 7;
    int count = 0;
    cout<<f(n, count)<<" "<< count;
}

Upvotes: 0

Related Questions