缓存代码问题

robin622 2014-01-20 11:41:00
我刚接触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;
}

我的问题用红字标识了,望高手指教,谢谢!!!
...全文
234 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
lm_whales 2014-03-26
  • 打赏
  • 举报
回复
这种替换,比较偏门,一般只有某些库代码会这么做。 正常的程序编写中,多半不会使用这样的代码。
lm_whales 2014-03-26
  • 打赏
  • 举报
回复
预编译的宏替换规则,不是这么做的。 你需要符号替换才行,需要用到 ##这个符号。 看看MFC的那些宏,是如何实现的,你就明白该怎么做了。 你这个替换,达不到你的目的。 单纯的宏替换,只是字符串的直接替换,不能做符号替换,除非使用 ##这个符号连接符。 也就是说: Cache(fib2) 被替换成 name_cache,而不是 fib2_cache CacheProc(fib2) 被替换成name_patch,而不是 fib2_patch 改成这样就可以了: #define PasteSym(x,y) x##y #define Cache(name) PasteSym(name,_cache) #define CacheProc(name) PasteSym(name,_patch) 这样就会有如下替换效果: Cache(fib2) ---> fib2_cache CacheProc(fib2) ---> fib2_patch
robin622 2014-01-24
  • 打赏
  • 举报
回复
麻烦哪位能回答下红字的问题啊。
robin622 2014-01-21
  • 打赏
  • 举报
回复
name_path 在下面代码中没找到,所以他如何被替换呢?
dcw0402 2014-01-21
  • 打赏
  • 举报
回复
引用 2 楼 robin622 的回复:
name_path 在下面代码中没找到,所以他如何被替换呢?
干么要找到呢? 替换就是
赵4老师 2014-01-21
  • 打赏
  • 举报
回复
编译选项加/EP /P,重新编译,查看宏展开后对应的.i文件。gcc加-E
derekrose 2014-01-20
  • 打赏
  • 举报
回复
#define就是简单的替换而已

70,022

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧