DEV Community

Cover image for Default parameters in C

Default parameters in C

Remo Dentato on January 08, 2021

Variadic functions Modern languages (like Python or Javascript) have a nice feature: they allow a function to have a variable number of ...
Collapse
 
magikz_d4800d6bc59a58bfe9 profile image
magikz

This is awesome, thank you for making this post!

I needed this to handle 0 arguments as well, so I made a small modification to this macro in order to make the first comma optional,

from:
#define vrg_argn(...) vrg_cnt(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1, 0)
to:
#define vrg_argn(...) vrg_cnt(__VA_ARGS__ __VA_OPT__(,) 8, 7, 6, 5, 4, 3, 2, 1, 0)

I'm not a macro wizard so I'm unsure how good/bad this may be but it solved my problem so I'm leaving this comment in case anyone else comes along with my same requirement.

Collapse
 
rdentato profile image
Remo Dentato

Thanks magikz.

That's a good solution and much simpler than the one currently used to handle zero arguments.

I'm not adopting it yet because VA_OPT is only available in C23 which is still to be promoted from its "draft" state to an official standard (I believe it's expected to happen very soon).

I know many compilers already support it, but I tried to use only C11 features to minimize incompatibilities between compilers.

Thanks for your suggestion!

Collapse
 
seanlumly profile image
Sean Lumly

Neat!

I like the argument counting. It is quite a clever use of the variadic macro, effectively "pushing" the argument count value into range with the number of arguments. I've not seen this before, nor considered it.

I was never a fan of variadic functions either, and this gets me thinking of other creative ways to mimic the behaviour.

Collapse
 
dynamicsquid profile image
DynamicSquid

I love how C doesn't have any "modern" features, but C devs are like screw it, we'll figure out a way ourselves

Collapse
 
basketcree profile image
basketcree

It's really astonishing way to using "default parameters" in c.
i love way you do it.