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);
}
The best way to implement a variable that keeps its state between function calls is to use the static keyword.
The Output will be:
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.