Saturday, June 14, 2014

Named arguments in C

When experimenting with some C99 features of C, I found a very cool trick to have named parameters, using a feature called designated initializers. The first time I read about designated initializers I must admit I found it to be pretty useless, but as I started testing it out, I ended up finding it very useful, since it can make code a lot more readable. Using it together with variadic macros, it was possible to have a very clean named parameter system.

Straight into the code, this is the technique:
typedef struct { int year; const wchar_t *name; } Foo_args; // parameters
void Foo_func(Foo_args args) {
	int x = args.year + 10; // use the argument
}
#define Foo(...) Foo_func((Foo_args){ __VA_ARGS__ })
And this is how you call the function:
Foo(.year = 2014, .name = L"Rodrigo");
The function calling is clear, and its implementation doesn’t add much noise to the code: I believe the price is payable and the result is worth.

No comments: