Search code examples
cnamed-parameters

Is there a nicer way to do c named arguments?


I'm trying to implement a flexible debug macro/function lib and named/optional arguments seem like the best way to implement the functions.

Is there a nicer way to do named arguments in c 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(...
        ...
        }
        ...
    }
    ...
}

Solution

  • Sure.

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

    or if you want you may wrap that in a macro

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