Creating and Initializing structs with variable length macro in C -


i trying create , initialize struct using variable length macro. want able create/initialize struct '0's , initialize fields of struct values optionally passed in.

is possible do? trying following:

#define init_entry(x, ...) \     entry_t x = {.id = 0, .age = 0} \     x.id  = <i want use arg1 here>     x.age = <i want use arg2 here if exists>  

is there way accomplish this?

it can done combination of argument counting , concatenation.

  1. first need macro counts it's arguments, i'll call nargs asked , answered here. note answers compiler-dependent.

  2. next need series of macros specific cases:

    #define init_entry_0(x) entry_t x = {.id = 0, .age = 0}
    #define init_entry_1(x, _id) entry_t x = {.id = _id, .age = 0}
    #define init_entry_2(x, _id, _age) entry_t x = {.id = _id, .age = _age}

  3. you need concatenation macro:

    #define concat(a, b) a##b

  4. last, use concatenation choose correct one:

    #define init_entry(x, ...) concat(init_entry_, nargs(__va_args__))(x, #__va_args__)


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -