Skip to content

Instantly share code, notes, and snippets.

@camel-cdr
Last active June 18, 2021 12:33
Show Gist options
  • Save camel-cdr/52b5eaf11739ff08f9a3c778b7bf97f8 to your computer and use it in GitHub Desktop.
Save camel-cdr/52b5eaf11739ff08f9a3c778b7bf97f8 to your computer and use it in GitHub Desktop.
ranged designated initializers in c99
#include <stdio.h>
#define E2(...) E1(E1(E1(E1(E1(E1(E1(E1(E1(E1(__VA_ARGS__))))))))))
#define E1(...) __VA_ARGS__
#define EMPTY()
#define DEFER1(m) m EMPTY()
#define APPLY3(F,a,x,y,v) F(a,0,x,y,v), F(a,1,x,y,v), F(a,2,x,y,v), \
F(a,3,x,y,v), F(a,4,x,y,v), F(a,5,x,y,v), \
F(a,6,x,y,v), F(a,7,x,y,v), F(a,8,x,y,v), \
F(a,9,x,y,v)
#define APPLY3_() APPLY3
#define F(a,b,x,y,v) [(a*10+b)>=x && (a*10+b)<=y?(a*10+b):0]=v
#define F10(a,b,x,y,v) DEFER1(APPLY3_)()(F, a*100+b, x, y, v)
#define F100(a,b,x,y,v) DEFER1(APPLY3_)()(F10, a*1000+b, x, y, v)
#define F1000(a,b,x,y,v) DEFER1(APPLY3_)()(F100, a*10000+b, x, y, v)
#define F10000(a,b,x,y,v) DEFER1(APPLY3_)()(F1000, a*100000+b, x, y, v)
#define F100000(a,b,x,y,v) DEFER1(APPLY3_)()(F10000, a*1000000+b, x, y, v)
#define F1000000(a,b,x,y,v) DEFER1(APPLY3_)()(F100000, b, x, y, v)
#define RANGE(min,max,val) E2(DEFER1(APPLY3_)()(F100, 0, min, max, val))
int tbl[] = {
RANGE('a', 'z', 42),
RANGE('A', 'Z', 42),
RANGE('0', '9', 42),
[0] = 0; /* make sure to set [0], because it's overwritten by RANGE */
};
int
main(void)
{
for (int i = 0; i < 256; ++i)
if (tbl[i] == 42)
putchar(i);
putchar('\n');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment