Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Macro expansion into multiple function calls

Is it possible to write a preprocessor macro such that would transform a variable number of arguments into successive function calls, such as

MAP(f, 1, 2, 3, ..., n)

into

f(1); f(2); f(3); ... f(n);

So far, I've got following, which seems to work:

#define MAP(f, t, ...) \
{\
    t __varlist[] = {__VA_ARGS__};\
    for(int i = 0; i < sizeof(__varlist) / sizeof(t); i++)\
        f(__varlist[i]);\
}

Note that this macro takes a type parameter so that it can be a bit more useful.

Is there a way to do it without declaring a temporary? Or does it not matter, because the compiler is so smart that it figures out everything? I'm kind of new to C.

like image 337
Gleno Avatar asked Oct 22 '22 05:10

Gleno


1 Answers

use boost.

note:limit size 256. BOOST_PP_LIMIT_SEQ

#include <stdio.h>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/tuple/size.hpp>
#include <boost/preprocessor/tuple/to_seq.hpp>

#define PROC(r, f, elem) f(elem);
//#define MAP(f, ...) BOOST_PP_SEQ_FOR_EACH(PROC, f, BOOST_PP_TUPLE_TO_SEQ(BOOST_PP_TUPLE_SIZE((__VA_ARGS__)),(__VA_ARGS__)))
#define MAP(f, ...) BOOST_PP_SEQ_FOR_EACH(PROC, f, BOOST_PP_TUPLE_TO_SEQ((__VA_ARGS__)))

void f(int data){
    printf("%d\n", data);
}

int main(){

    MAP(f, 1, 2, 3);
    return 0;
}
like image 136
BLUEPIXY Avatar answered Nov 12 '22 21:11

BLUEPIXY