Sujet : Re: Named arguments in C
De : bluemanedhawk (at) *nospam* invalid.invalid (Blue-Maned_Hawk)
Groupes : comp.lang.cDate : 03. Jul 2024, 21:42:22
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <pan$39bde$c80409dd$374fc6fd$c86207fe@invalid.invalid>
References : 1 2 3 4 5 6 7
User-Agent : Pan/0.154 (Izium; 517acf4)
bart wrote:
On 02/07/2024 20:39, Blue-Maned_Hawk wrote:
I searched around a bit, and it seems like a more common way to
implement named arguments in C is with a pattern like this:
#define f(...) f_impl((struct f_struct){__VA_ARGS__})
void f_impl(struct f_struct { int i, j; char * k; double l, m, n; }
f_params)
{
/* actual code */
You missed out accesses to the parameters which would look like
f_params.i and f_params.m.
Apologies—i assumed that it woudl be obvious that that's how it would be
done.
}
int main(void)
{
f(.i = 0, .j = 2, .l = 2.5, .k = "foo", .n = 4.2, .m = 2.5);
}
This addresses a small part of it. Named parameters allow arguments to
be omitted, and that requires also default values to be defined.
I think there's a difference of nomenclature here, because i would
consider named parameters to _only_ imply the ability to name parameters,
and not necessarily imply parameter omission.
Nevertheless, while searching around, i _did_ see people describe a way to
assign default parameter values with a feature that i can confidently say
i've never seen used anywhere else: the ability to specify designated
initializers twice and have the latter override the first.
You can make ever more complex schemes to emulate them in C, but the
boilerplate will just increase.
On the other hand, some boilerplate could be alleviated: we could get a
result of
#define f(...) DEF(f, .i = 1, .j = 2, .k = "blah", __VA_ARGS__)
void DEC(f, int i, j; char * k; double l, m, n;)
{
/* actual code */
}
through the macros
#define DEF(name, ...) name##_impl((struct name##_struct){__VA_ARGS__})
#define DEC(name, ...) name##_impl(struct name##_struct {__VA_ARGS__}
name##_params)
which, while not perfect (i'm not a fan of the __VA_ARGS__ repetition
necessary in DEF), do make things better and probably a little less error-
prone.
(Apparently, the P99 preprocessor library also has some macros in it to
allow for default subroutine arguments. I have done absolutely no
research into how these work or whether they're any good.)
But at least, this allows parameters with the same type to be declared
as:
double l, m, n
instead of:
double l, double m, double n
I'm going to go out on a limb here and assume that the former form would
have caused some sort of grammatical ambiguity/complexity issues when
prestandard declarations were still in the standard, but _might_ be
implementable nowadays now that they've been removed from the standard.
-- Blue-Maned_Hawk│shortens to Hawk│/blu.mɛin.dʰak/│he/him/his/himself/Mr.blue-maned_hawk.srht.siteIt would be disasterous!