Keep track of how many times a recursive function has been called in C++

I've seen quite a mess here so I decided to clear the things out.

Solution 0: Static Variable

Consider the code proposed with a small modification

#include<iostream>
using namespace std;

void fun()
{
    static int count=1;
    count++;
    cout << "fun() is called " << count << " times" << endl;
    if(count<=10)
    {
            fun();
    }
}

int main()
{
    cout << "first call" << endl;
    fun();
    cout << "second call" << endl;
    fun();
    cout << "third call" << endl;
    fun();
}

resulting in this output:

first call
fun() is called 2 times
fun() is called 3 times
fun() is called 4 times
fun() is called 5 times
fun() is called 6 times
fun() is called 7 times
fun() is called 8 times
fun() is called 9 times
fun() is called 10 times
fun() is called 11 times
second call
fun() is called 12 times
third call
fun() is called 13 times

As you can see, using static variables could lead to some unexpected behaviour.

This is a one shot function that will cause you quite some headaches in the future. Furthermore, the usage of static variables leads to an unreadable code that is error prone

Just don't do it!

Solution 1: Variable passed by value

Consider this code:

#include <iostream>
using namespace std;

void fun(int i){
    cout<<i<<endl;
    if(i!=3) {
        i++;
        fun(i);
        fun(i);
    }
}

int main(){
    fun(0);
}

This is the output:

0
1
2
3
3
2
3
3
1
2
3
3
2
3
3

As you can see the output is not the number of times the function is called

Solution 2: Variable passed by reference

#include <iostream>
using namespace std;

void fun(int& x){
    if(x>=10)
        return;
    ++x;
    cout << x << endl;
    fun(x);
}

void funEntry(){
    int x = 0;
    cout << "Entry point" << endl;
    fun(x);
}

int main(){
    funEntry();
    funEntry();
}

will print

Entry point
1
2
3
4
5
6
7
8
9
10

This approach will work also with some more exotic recursive pattern like this one

#include <iostream>
using namespace std;

void fun(int i, int& x){
    if(i>=4)
        return;
    ++x;
    cout << i << " " << x << endl;
    fun(i+1,x);
    fun(i+2,x);
}

void funEntry(){
    int x = 0;
    cout << "Entry point" << endl;
    fun(0,x);
}

int main(){
    funEntry();
    funEntry();
}

Output:

Entry point
0 1
1 2
2 3
3 4
3 5
2 6
3 7
Entry point
0 1
1 2
2 3
3 4
3 5
2 6
3 7

Add a static variable as counter.

#include<iostream>
using namespace std;

void fun()
{
    static int count=1;
    count++;
    cout << "fun() is called " << count << " times" << endl;
    if(count<=10)
    {
            fun();
    }
}

int main()
{
    fun();
}

static variables are initialized only once and the value will be retained across function calls. See this link http://en.wikipedia.org/wiki/Static_variable