Why does this macro not work like I think it would?

Viewed 57

I'm a little new to C still, so bear with me.

I am attempting to be able to refer to the elements of a structure via an index. I figured a macro would do the trick, but evidently not. Can anyone explain why the following does not work?

#include <stdio.h>

#define E(Structure, Index) Structure.var_Index

typedef struct test{
    int var_0;
}TEST;

int main(){
    TEST Test;
    
    E(Test, 0) = 0;
    
    return(0);
}

My IDE says "No member named 'var_Index' in 'struct test'," but I have no # in front of the word Index in the macro.

2 Answers

Merging tokens is done with ##

The following change should work:

#define E(Structure, Index) Structure.var_##Index

var_Index is one token and the compiler (preprocessor) won't see as Index.

You can use ## operator to have it concatenate tokens in macros.

#include <stdio.h>

#define E(Structure, Index) Structure.var_##Index

typedef struct test{
    int var_0;
}TEST;

int main(){
    TEST Test;
    
    E(Test, 0) = 0;
    
    return(0);
}
Related