Search code examples
cmacrosstructurec-preprocessor

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


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.


Solution

  • Merging tokens is done with ##

    The following change should work:

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