c - C 宏中未声明(在此函数中首次使用)

标签 c c-preprocessor

#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/

相关文章:

c - 对 sqlite_open 的 undefined reference

c++ - 分析有或没有优化的代码

c - 涉及 sin() 的两个非常相似的函数表现出截然不同的性能——为什么?

C 是否可以使用结构变量进行定义?

c - 在 C 中生成路径的最佳方法是什么?

c++ - Boost Wave 不能做什么?

C桶字符串

objective-c - 如何检测是否正在使用/从 Swift 编译 Objective-C header

c - 在 C 中有条件地包含数据表列的最佳方法

c - 在这个对矩阵进行不同操作的程序中,如果没有产生正确的输出,则 saddlepoint() 函数。为什么?