2
#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));
      |                   ^~~~~~

所以你能帮我得到答案吗

例如

COURSE(1) 应该把我打印出来 4

COURSE(2) 应该把我打印出来 5

4

2 回答 2

2

错误在第 10 行
#define COURSE(number) CREDITS_COURSE##number
你不能使用这个声明

不能像这样在循环内的运行时调用宏。您可以声明一个常量数组并初始化所有元素

const int credits_course[8] = {4, 5, 4, 4, 3, 3, 2, 3};

这是C代码:

#include<stdio.h>    

const int credits_course[8] = {4, 5, 4, 4, 3, 3, 2, 3};

int main()
{   for(int i=0;i<8;i++)
    printf("%d\n",credits_course[i]);
    
    return 0;
}
于 2020-11-24T09:19:57.280 回答
2

您绝对不能在运行时调用动态变量名。并且绝对不能用宏来做到这一点。

您可以改为声明一个数组const以使其不可变:

const int CREDITS_COURSE[8] = {4, 5, 4, 4, 3, 3, 2, 3};

或使用enumeration

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;
于 2020-11-24T08:44:41.110 回答