Static and Global in Recursion


#include <cstdio>

int fun(int n) {
  static int x = 0;

  if (n > 0) {
    x++;
    return fun(n - 1) + x;
  }
  return 0;
}

int main() {
  int r;
  r = fun(5);
  printf("%d", r); // 25

  r = fun(5);
  printf("%d", r); // 50
}

  • Static variables are created inside the code section, or there is a sub section of code section called as section for global variables and static variables.

Will this static variable be created every time whenever the function is called? No, it will not be created every time. It will be created only once, at the loading time of a program. The "x" variable in this program will not have multiple copies, like "n".

  • At the end of this function, the result of "x" will be 5, and will be reused in each recursive call. They will behave like variables that are outside of the function, maintaining a single copy. It would be the same as using a global variable.