am12345
am12345

Reputation: 33

How to create a function-like macro token by pasting tokens together

I have a set of predefined macros (That I cannot change) where each one takes as input the index for an array. I want to create another macro to be able to choose which previously defined macro to use by pasting the tokens together.

I have tried creating a macro that takes in 2 arguments: x, which picks which previously defined macro to use, and ind, which is passed on to the selected macro.

The code below is ran using https://www.onlinegdb.com/online_c_compiler so I can figure out the basic code before I put it into a rather large application.

#include <stdio.h>

//struct creation
struct mystruct {
    int x;
    int y;
};

//create array of structs
struct mystruct sArr1[2] = {{1,2},{3,4}};
struct mystruct sArr2[2] = {{5,6},{7,8}};

//define macros
#define MAC1(ind) (sArr1[ind].x)
#define MAC2(ind) (sArr2[ind].y)

// Cannot change anything above this //

//my attempt at 2 input macro
#define MYARR(x,ind) MAC ## x ## (ind)

int main() {
    printf("%d\n", MYARR(1, 0));
    return 0;
}

I want the result to print out the x value of sArr1 at index 0, which is 1. Instead, I get this output

main.c: In function ‘main’:
main.c:29:22: error: pasting "MAC1" and "(" does not give a valid preprocessing token
 #define MYARR(x,ind) MAC ## x ## (ind)
                      ^
main.c:33:19: note: in expansion of macro ‘MYARR’
     printf("%d\n", MYARR(1, 0));

Upvotes: 3

Views: 295

Answers (1)

Brad Pitt
Brad Pitt

Reputation: 416

line 29 should be :

#define MYARR(x,ind) MAC##x(ind)

I tested it. It printed '1', which is what you want.

Upvotes: 1

Related Questions