#define CREDITS_COURSE1 4
#define CREDITS_COURSE2 5
#define CREDITS_COURSE3 4
#define CREDITS_COURSE4 4
#define CREDITS_COURSE5 3
#define CREDITS_COURSE6 3
#define CREDITS_COURSE7 2
#define CREDITS_COURSE8 3
#define COURSE(number) CREDITS_COURSE##number
int main()
{ for(int i=1;i<9;i++)
printf("%d\n",COURSE(i));
}
我期望它打印各自定义的值 但它显示错误
error: 'CREDITS_COURSEi' undeclared (first use in this function); did you mean 'CREDITS_COURSE1'?
10 | #define COURSE(number) CREDITS_COURSE##number
| ^~~~~~~~~~~~~~
cc.c:14:19: note: in expansion of macro 'COURSE'
14 | printf("%d\n",COURSE(i));
| ^~~~~~
cc.c:10:24: note: each undeclared identifier is reported only once for each function it appears in
10 | #define COURSE(number) CREDITS_COURSE##number
| ^~~~~~~~~~~~~~
cc.c:14:19: note: in expansion of macro 'COURSE'
14 | printf("%d\n",COURSE(i));
| ^~~~~~
你能帮我得到答案吗
例如
类(class)(1)应该打印出我 4
类(class)(2)应该打印出5
最佳答案
你绝对不能在运行时调用动态变量名。而且绝对不能用宏来做到这一点。
您可以将数组声明为 const
以使其不可变:
const int CREDITS_COURSE[8] = {4, 5, 4, 4, 3, 3, 2, 3};
或者使用枚举
:
enum {
course_1 = 4,
course_2 = 5,
course_3 = 4,
course_4 = 4,
course_5 = 3,
course_6 = 3,
course_7 = 2,
course_8 = 3
} CREDITS_COURSE;
关于c - C 宏中未声明(在此函数中首次使用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64982773/