Is there a better way to do with named arguments?

I am trying to implement a flexible debug macro / function lib, and named / optional arguments are the best way to implement functions.

Is there a better way to execute named arguments in c and then the following?

enum named_args {NAME,ADRESS,AGE,NA_SENTINEL}; void named_arg_initializers(struct person p, enum * named_args) { enum named_args * current_name; enum named_args * current_arg; ... if(named_args==NULL) return; current_name = named_args[0]; current_arg = named_args[1]; while(current_name!=NA_SENTINEL) { current_name+=2; current_arg+=2; if(current_name==NAME) p.name=current_arg; else if(... ... } ... } ... } 
+6
source share
2 answers

Of course.

 struct toto { unsigned age; char name[25]; }; void func(struct toto); ... func((struct toto){ .name = "you", .age = 18 }); 

or if you want, you can wrap it with a macro

 #define FUNC(...) func((struct toto){ __VA_ARGS__ }) ... FUNC(.name = "you", .age = 18 ); 
+17
source

What you showed is not valid if the named arguments are not compatible with enum (you can fix this with the void * argument).

However, you can do something similar with varargs, which looks more neat:

 #include <stdarg.h> enum named_args { NAME, ADDRESS, AGE, NA_SENTINEL }; void named_arg_initializers(struct person *p, ...) { va_list ap; enum named_args argn; va_start(ap, p); for (argn = va_arg(ap, enum named_args); argn != NA_SENTINEL; argn = va_arg(ap, enum named_args)) { switch (argn) { case NAME: p->name = va_arg(ap, char *); break; case AGE: p->age = va_arg(ap, int); break; /* ... */ } } va_end(ap); /* ... */ } 

You would use it like this:

 named_arg_initializers(&p, AGE, 110, NAME, "Claude Choules", NA_SENTINEL); 
+1
source

Source: https://habr.com/ru/post/887698/


All Articles