宏使用的疑问

yangyunzhao 2018-06-26 05:52:25

#define random_reslev(_ResType) random(Res##_ResType##Levs[0], Res##_ResType##Levs[1])



// 代码1
int lev = random_reslev(1); // 正确

// 代码2
int type = 1;
int lev = random_reslev(type); // 编译失败


请改如何使用才可以实现代码2的目标?谢谢
...全文
183 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
真相重于对错 2018-06-27
  • 打赏
  • 举报
回复
宏相当于源文件的文本替换。
第一个直接用1替换对应的代码
第二个是个变量,能替换吗?
donjin9 2018-06-27
  • 打赏
  • 举报
回复
这宏属于预编译,比编译更早。不能这样用吧,还是得用数组。
yangyunzhao 2018-06-27
  • 打赏
  • 举报
回复
求助,谢谢!
赵4老师 2018-06-27
  • 打赏
  • 举报
回复
//codegen.c
// 输入一组字符串,比如
// aa ss ddd dd 33 dd
// 然后自动生成一个函数 int A(const char*);
// 实现A("aa")返回0 A("ss")返回1 依次类推
#include <stdio.h>
int main(int argc,char **argv) {
int i;
if (argc<2) {
printf("%s p1 [p2 ...] [>result.c]\nGenerate code int A(const char *a); 0==A(\"p1\") 1==A(\"p2\") ...",argv[0]);
return 1;
}
//printf("#include <string.h>\n");
printf("int A(const char *a) {\n");
for (i=0;i<argc-1;i++) {
printf(" if (0==strcmp(a,\"%s\")) return %d;\n",argv[i+1],i);
}
printf(" return -1;\n");
printf("}\n");
return 0;
}
//C:\test\Debug>codegen.exe
//codegen.exe p1 [p2 ...] [>result.c]
//Generate code int A(const char *a); 0==A("p1") 1==A("p2") ...
//C:\test\Debug>codegen.exe aa ss ddd dd 33 dd
//int A(const char *a) {
// if (0==strcmp(a,"aa")) return 0;
// if (0==strcmp(a,"ss")) return 1;
// if (0==strcmp(a,"ddd")) return 2;
// if (0==strcmp(a,"dd")) return 3;
// if (0==strcmp(a,"33")) return 4;
// if (0==strcmp(a,"dd")) return 5;
// return -1;
//}
//
//c:\test\Debug>codegen.exe aa ss ddd dd 33 dd >result.c
//
//c:\test\Debug>type result.c
//int A(const char *a) {
// if (0==strcmp(a,"aa")) return 0;
// if (0==strcmp(a,"ss")) return 1;
// if (0==strcmp(a,"ddd")) return 2;
// if (0==strcmp(a,"dd")) return 3;
// if (0==strcmp(a,"33")) return 4;
// if (0==strcmp(a,"dd")) return 5;
// return -1;
//}
//
赵4老师 2018-06-27
  • 打赏
  • 举报
回复
了解一下代码生成技术。
yangyunzhao 2018-06-26
  • 打赏
  • 举报
回复
引用 楼主 yangyunzhao 的回复:

#define random_reslev(_ResType) random(Res##_ResType##Levs[0], Res##_ResType##Levs[1])



// 代码1
int lev = random_reslev(1); // 正确

// 代码2
int type = 1;
int lev = random_reslev(type); // 编译失败


请改如何使用才可以实现代码2的目标?谢谢


// 变量定义类似这样
int Res0Levs[2]={10,20};
int Res1Levs[2]={20,35};
int Res2Levs[2]={40,80};


70,021

社区成员

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

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