C Macro to remove duplicates in list of arguments

417 Views Asked by At

I wonder if it is possible to build a gnu C macro which expands to a list of tokens (integer numbers) which are the arguments of the macro without duplicates. The number of arguments could be assumed fixed (for the moment). I.e. I want something like:

#define MAC(a,b,c) ???

which expands e.g.

MAC(1,2,1)

to 1,2. The arguments are not sorted and the result does not have to be.


Based on the proposal below I built an example which does essentially what I want using the p99 includes:

#include <p99/p99_if.h>
#include <p99/p99_paste.h>

#define MAC2(a,b) double P99_PASTE2(myvar_, a) P99_IF_EQ(a,b)()(; double P99_PASTE2(myvar_, b))
#define MAC3(a,b,c) double P99_PASTE2(myvar_, a) P99_IF_EQ(a,b)()(; double P99_PASTE2(myvar_, b)) P99_IF_EQ(a,c)()(P99_IF_EQ(b,c)()(; double P99_PASTE2(myvar_, c)) )

MAC2(1,2);
MAC2(3,3);

MAC3(1,2,3);
MAC3(10,10,1);
1

There are 1 best solutions below

4
On BEST ANSWER

If your arguments are always small decimal numbers as in your example, you could get away with what I provide in P99. It has macros like P99_IF_EQ that you could use as

#define MAC(A,B) unsigned P99_PASTE2(myvar_, A) P99_IF_EQ(A,B)()(; unsigned P99(unsigned P99_PASTE2(myvar_, B))

MAC(1,2); // -> myvar_1 and myvar_2
MAC(3,3); // -> myvar_3

to only expand the declaration for B if it is not equal to A. Obviously for three different arguments this already becomes a bit tedious, but would be doable.