Macro recursive extension to sequence

Is it possible to define a C / C ++ " BUILD(a, i)" macro that expands to " x[0], x[1], x[2], ..., x[i]"? How in

#define BUILD(x, 0) x[0]
#define BUILD(x, 1) x[0], x[1]
#define BUILD(x, 2) x[0], x[1], x[2]
...

It seems BOOST_PP_ENUM_PARAMS can do the job. I suppose I could just turn on # boost, but I'm curious to know how and why this works, can anyone explain?

I would like to call a function f(int, ...)that accepts N int arguments x[i], 0 <= i <N. The Where it is known that of N ceil(sizeof(A) / sizeof(B)). Unfortunately, I cannot use varargs or templates.

+5
source share
3 answers

Perhaps, but you need to do manual work and have an upper limit.

#define BUILD0(x) x[0]
#define BUILD1(x) BUILD0(x), x[1]
#define BUILD2(x) BUILD1(x), x[2]
#define BUILD3(x) BUILD2(x), x[3]
#define BUILD(x, i) BUILD##i(x)

, i , .

BTW, , , . Boost , , . . . , .

: boost . , , ..... , , . , , , , .

#define BUILD_(x, i) BUILD##i(x)
#define BUILD(x, i) BUILD_(x, i)

#define FOO 42
BUILD(x, FOO)

, .

+14

, : . , , " ".

+2

Ok, . , N . , . , .

#define HEX_ARRAY_AS_STR(array, len) \
    ({ \
        int print_counter = 0; \
        print_buf = calloc(len*3+1, 1); \
        char *tmp_print_buf = print_buf; \
        uint8_t *array_flower = array;  \
        while(print_counter++ < (len)){ \
            sprintf(tmp_print_buf, "%02X ", *(array_flower)++); \
            tmp_print_buf += 3; \
        } \
        print_buf; \
    })

#define eprintf(...) \
    do{ \
        char *print_buf; \
        printf(__VA_ARGS__); \
        if(print_buf) \
            free(print_buf); \
    }while(0)

int 
main(int argc, char *argv[])
{
    uint8_t sample[] = {0,1,2,3,4,5,6,7};
    eprintf("%s\n", HEX_ARRAY_AS_STR(sample, 8));
    return 0; 
}
0

All Articles