Undeclared (first use in this function) in C Macro

Viewed 1808
#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));
}

I am expecting it to print respective value defined but instead it is showing the error

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

So can you please help me to get the answer

For Example

COURSE(1) should print me out 4

COURSE(2) should print me out 5

2 Answers

You absolutely can't call dynamic variable names run-time. And absolutely can't do it with macros.

You can instead declare an array as const to make it immutable:

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

Or using an 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;

The error is in line 10
#define COURSE(number) CREDITS_COURSE##number
You cannot use this declaration

Macros cannot be called in run time within loop, like that. You can declare a constant array and initialize all the elements

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

Here is the C code:

#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;
}
Related