缓存代码问题
我刚接触C,看到一段代码,有些问题,希望帮下忙,谢啦!这个一段用C实现缓存的代码,如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//NIL must be nicety
#define NIL (-1)
#define CACHESIZE 1024
#define CacheProc(name) name_patch ///why name_path can not be found in the code???????????????
#define Cache(name) name_cache ///where is the definition of "Cache"??????????
#define InitCacheFor(name) memset(name_cache,NIL,CACHESIZE*sizeof(int))
#define GEN_CACHE_PROC(name)\
int Cache(name)[CACHESIZE];\
int CacheProc(name)(int n)\
{\
if(Cache(name)[n]==NIL)\
{\
Cache(name)[n]=name(n);\
};\
return Cache(name)[n];\
}
int fib(int);
int fib2(int);
int CacheProc(fib2)(int);
int fib(int n) {
if (n <= 2)
return 1;
else
return fib(n - 2) + fib(n - 1);
}
/**
to keep form as fib
just need to call CacheProc
保持算法形式上和fib一样
**/
int fib2(int n) {
printf("fib2 be called:%d/n", n);
if (n <= 2)
return 1;
else
return CacheProc(fib2)(n - 2) + CacheProc(fib2)(n - 1);
}
/** to creat
int Cache(fib2)[CACHESIZE];
int CacheProc(fib2)(int n)
{
if(Cache(fib2)[n]==NIL)
{
Cache(fib2)[n]=fib2(n);
};
return Cache(fib2)[n];
}
use GEN_CACHE_PROC**/
GEN_CACHE_PROC(fib2);
//
int main() {
InitCacheFor(fib2);
while (1) {
int N;
printf("intput N (<=0 exit):");
if (scanf("%d", &N) == 1) {
if (N >= 1) {
printf("fib(%d)=%d/n", N, fib(N));
printf("cached fib2(%d)=%d/n", N, fib2(N));
} else {
exit(0);
};
} else {
char bad[1024];
scanf("%s", bad);
}
};
return 0;
}
我的问题用红字标识了,望高手指教,谢谢!!!