Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending 0s to an incomplete macro parameter list

I have the following couple of C preprocessor macros that I use:

#define TAKE4(a1, a2, a3, a4, ...) a1, a2, a3, a4
#define FILL_PARAMS(...) TAKE4(__VA_ARGS__, 0, 0, 0, 0)

When calling FILL_PARAMS with 1, 2, or 3 parameters, the later (unspecified) are turned into 0s as expected, but when giving no arguments there's an error.

Is there a way to add support for no-parameters?

Clarification:
Currently the following uses are supported:

FILL_PARAMS(1)         // => 1, 0, 0, 0
FILL_PARAMS(1, 2)      // => 1, 2, 0, 0
FILL_PARAMS(1, 2, 3)   // => 1, 2, 3, 0

And I want to add support for the following edge case:

FILL_PARAMS()          // => 0, 0, 0, 0

Help will be welcome.

like image 955
Gilad Naaman Avatar asked Apr 29 '16 10:04

Gilad Naaman


1 Answers

Found a hack-ish solution:

#define TAKE4(a1, a2, a3, a4, ...) a1, a2, a3, a4
#define FILL_PARAMS(...) TAKE4( __VA_ARGS__ + 0, 0, 0, 0, 0)

That works with at-least the following test-cases.

int i = 120;
printf("%d\t%d\t%d\t%d\n", FILL_PARAMS());
printf("%d\t%d\t%d\t%d\n", FILL_PARAMS(i));
printf("%d\t%d\t%d\t%d\n", FILL_PARAMS(1));
printf("%d\t%d\t%d\t%d\n", FILL_PARAMS(1, 2));
printf("%d\t%d\t%d\t%d\n", FILL_PARAMS(1, 2, 3));
printf("%d\t%d\t%d\t%d\n", FILL_PARAMS(1, 2, 3, 4));
printf("%d\t%d\t%d\t%d\n", FILL_PARAMS(1, 2, 3, i));
like image 69
Gilad Naaman Avatar answered Sep 28 '22 22:09

Gilad Naaman