Search code examples
c++variable-declaration

Declaring variable in recursive function C++


I wish to declare a variable w inside a recursive function. I have to declare it as f(a) (some function of a) where a is a parameter of the function. The problem is that the function is recursive and w changes value every time the recursive function is called (since a changes)

Is there a way to do keep w fixed to its first initialization?

#include <iostream>
using namespace std;

void foo(int a)
{ 
    if(a==1) return 0;
    // int w = f(a);
    //...some more lines of code that use 'w'
    // eg. return foo(a - 1);
}

Solution

  • The best way to implement a variable that keeps its state between function calls is to use the static keyword.

    int AddOne_Static(void) {
        static int a;
        
        a++;
        
        return a;
    }
    
    int AddOne(void) {
        int a;
        
        a++;
        
        return a;
    }
    
    int main(void) {
        printf("%d\n", AddOne_Static());
        printf("%d\n", AddOne_Static());
        printf("%d\n", AddOne_Static());
        
        printf("%d\n", AddOne());
        printf("%d\n", AddOne());
        printf("%d\n", AddOne());
    }
    

    The Output will be:

    1
    2
    3
    
    1
    1
    1
    

    This is a much cleaner way of declaring a variable that will keep its value between calls than a global which will also pollute the global namespace unnecessarily.