vjain419
vjain419

Reputation: 253

how to add variable argument in c macro specific case

i am writing HW code and required to crate one macro where user can pass different argument. My macro will make sure that each argument get written on some memory location.

#define my_macro (.......) { \
   int *data1 = (int *) addr1 ; \  #if args1 is present
   int *data2 = (int *) addr2 ; \ #if args2 is presnet
   .
   .
   *data1 &= args1;
   *data2 &= args2;
   .
   .
}

ex1 : my_macro(data1,data2); ex2 : my_macro(data1,data2,data3,data4);

also data1 and data2 should be declare only when args is present. ex. if args is not present my_macro(data1) that case *data1 &= args1; should not be get declare.

tired to use __VA_ARGS__ thing but dont know how to separate out different variable so i can assign each args to data*

Please help here!

Upvotes: 0

Views: 225

Answers (1)

Filipe Gonçalves
Filipe Gonçalves

Reputation: 21213

There is an answer you can use from this question (the 3rd one): Is it possible to iterate over arguments in variadic macros?

I'd say something like:

#define my_macro (...) { \
do { \
    int i; \
    int _arr_args_[] = {__VA_ARGS__}; \
    for (i = 0; i < sizeof(_arr_args_)/sizeof(_arr_args_[0]); i++) \
        *(int *) addr_i &= _arr_args[i]; \
    } \
 } while(0)

This is equivalent to what you want to do; the only missing detail is exactly how you get addr_i - you didn't specify where this comes from, so I'll assume you just have some way to get it in your code. This, of course, assumes that the arguments you'll be passing are always of type int, which I guess is safe to assume, given the example you provided.

Upvotes: 2

Related Questions