I can think of several reasons:
debugging / testing (warning - did not check this code):
#include <stdio.h> #define MAX_INPUT 46 int runs=0; int fib1(int n){ ++runs; return n>2?fib1(n-1)+fib1(n-2):1; }; int fib2(int n,int *cache,int *len){ ++runs; if(n<=2){ if(*len==2) return 1; *len=2; return cache[0]=cache[1]=1; }else if(*len>=n) return cache[n-1]; else{ if(*len!=n-1) fib2(n-1,cache,len); *len=n; return cache[n-1]=cache[n-2]+cache[n-3]; }; }; int main(){ int n; int cache[MAX_INPUT]; int len=0; scanf("%i",&n); if(!n||n>MAX_INPUT) return 0; printf("fib1(%i)==%i",n,fib1(n)); printf(", %i run(s)\n",runs); runs=0; printf("fib2(%i)==%i",n,fib2(n,&cache,&len)); printf(", %i run(s)\n",runs); main(); };
I used moving variables for fib2, but this is another scenario in which global variables (pure mathematical functions that should store data to avoid them forever) can be useful.
programs used only once (for example, for a competition), or when development time needs to be reduced
globals are useful as typed constants, where a function somewhere requires * int instead of int.
I usually avoid global bindings if I intend to use the program for more than one day.
yingted Feb 19 2018-11-18T00: 00Z
source share