Search code examples
carraysx-macros

Compilation error when printing array elements in a X-Macro


I have the following code where I am using x-macro:

#define X_FIELDS  \
     X(int,        var1) \
     X(uint8_t,    var3) \
     X(uint16_t,   var4) \
     XA(uint8_t,   arr1, 4) \
     XB(char,      arr2, 2)

typedef struct {
#define X(type, name) type name;
#define XA(type, name, count) type name[count];
#define XB(type, name, count) type name[count];
    X_FIELDS
#undef X
#undef XA
#undef XB
} myStruct;

and a function to print the values:

void print(myStruct *aStruct)
{
  int i;
#define X(type, name) printf("mystruct.%s is %d\n", #name, aStruct->name);
#define XA(type, name, count) \
  for (i=0; i < count; i++) { \
      printf("element = %u\n", name[i]); \
  }
#define XB(type, name, count) \
  for (i=0; i < count; i++) { \
      printf("element = %c\n", name[i]); \
  }
X_FIELDS
#undef X
#undef XA
#undef XB
}

and the main function:

int main() {
  myStruct a = {.var1 = 23, .var4 = 12, .arr1 = {32,15,22,11} };
  print(&a);

}

Not sure why, but on the compilation, I get the following error: enter image description here

where the compiler is not able to see arr1, and arr2 provided I am able to see both in the pre-processor file. Following is the output of the pre-processor:

typedef struct {
    int var1; uint8_t var3; uint16_t var4; uint8_t arr1[4]; char arr2[2];
} myStruct;

void print(myStruct *aStruct)
{
  int i;
# 44 "C:\\Users\\akumar8\\CodeBlockWorkspace\\myTest\\myTest\\main.c"
printf("mystruct.%s is %d\n", "var1", aStruct->var1); printf("mystruct.%s is %d\n", "var3", aStruct->var3); printf("mystruct.%s is %d\n", "var4", aStruct->var4); for (i=0; i < 4; i++) { printf("element = %u\n", arr1[i]); } for (i=0; i < 2; i++) { printf("element = %c\n", arr2[i]); }
}

Any idea what am I doing wrong?


Solution

  • As you can see in the pre-processor output, the name in your macro evaluates to arr1 - it doesn't know that it is part of a aStruct.

    #define XA(type, name, count) \
      for (i=0; i < count; i++) { \
          printf("element = %u\n", name[i]); \
      }
    

    For the lines that do work, you're including the struct aStruct in the macro

    #define X(type, name) printf("mystruct.%s is %d\n", #name, aStruct->name);
    

    So you should also do the same here like this

    #define XA(type, name, count) \
      for (i=0; i < count; i++) { \
          printf("element = %u\n", aStruct->name[i]); \
      }