Home > Software engineering >  #define nested struct values in c
#define nested struct values in c

Time:08-10

I am working on C Structures. I want to #define the struct values as follows.

// #define get_x() { .y = { .z = 1, .c = "test" } };   // this is working

// But I want to replace the above line with 
#define get_y() { .z = 1, .c = "test" };
#define get_x() { .y = get_y() };                     // this gives error

struct :
typedef struct { 
    int z;
    char c[10]; 
} y_t;

typedef struct { 
    y_t y;
} x_t;

int main()
{
    x_t x = get_x();
    printf("c: %s", x.y.c);
    return 0;
}

Will you please help me know, How can I do that?

CodePudding user response:

Remove the ;, there is no ; in initialization. Typically, macros are in upper case.

#define GET_Y() { .z = 1, .c = "test" }
#define GET_X() { .y = GET_Y() }
  • Related