hailinzeng hailinzeng - 1 year ago 74
C Question

C macro to unroll fixed sized array declaration, rename each with index suffix

Is it possible to define a macro

, so that
int a[4]; void (INPUT_ARR(int, a, 4)){}
equals to
void (int a0, int a1, int a2, int a3){}

Answer Source

Here's one way:

#define INPUT_ARR(type, name, count) IARR ## count (type, name)

#define IARR0(type, name)
#define IARR1(type, name) type name##0
#define IARR2(type, name) IARR1(type, name), type name##1
#define IARR3(type, name) IARR2(type, name), type name##2
#define IARR4(type, name) IARR3(type, name), type name##3

void func (INPUT_ARR(int, a, 4)){}

int main()

Results of gcc -E (excluding main):

void func (int a0, int a1, int a2, int a3){}

You'll need to add IARR lines up until the max count that you want to support. It's not possible to have recursive macro definitions that go on automatically.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download