Knowledge Base
Authentication is disabled (development mode).

Concat arguments of variadic macro

Edit

append argument arguments c c++ chain concat glue macro preproc preprocess preprocessor vararg variable variadic

 #define glue(a, b)                        a ## b
#define concat(a, b)                      glue(a, b) // This is needed to expand `a` and `b`
#define shift1(a)                         a
#define shift2(a, b)                      a << b
#define shift3(a, b, c)                   a << shift2(b, c)
#define shift4(a, b, c, d)                a << shift3(b, c, d)
#define shift5(a, b, c, d, e)             a << shift4(b, c, d, e)
#define shift6(a, b, c, d, e, f)          a << shift5(b, c, d, e, f)
#define shift7(a, b, c, d, e, f, g)       a << shift6(b, c, d, e, f, g)
#define shift8(a, b, c, d, e, f, g, h)    a << shift7(b, c, d, e, f, g, h)
#define _8th(a, b, c, d, e, f, g, h, ...) h
#define count(...)                        _8th(x, ## __VA_ARGS__, 6, 5, 4, 3, 2, 1, 0)
#define chain(a, b, ...)                  a << concat(shift, count(b, ## __VA_ARGS__))(b, ## __VA_ARGS__)

int main(int argc, char **argv)
{
	// 0 << 1;
	chain(0, 1);
	chain(0, 1, 2);
	chain(0, 1, 2, 3);
	chain(0, 1, 2, 3, 4);
	chain(0, 1, 2, 3, 4, 5);
	chain(0, 1, 2, 3, 4, 5, 6);
	chain(0, 1, 2, 3, 4, 5, 6, 7);
	// 0 << 1 << 2 << 3 << 4 << 5 << 6 << 7;

	return 0;
}