There is no normal way to automate the filling of an array.
The best option is to do something different.
You can use one function:
void func_i(int i) { switch (i) {...} }
If you wrote in C ++, you can use lambda functions and place them immediately in an array of function pointers:
void (*array[])() = { [](){...}, [](){...}, [](){...}, };
Backup option:
It is possible to “automate” the process of filling an array with the help of serious macro-magic, but the end result will still be like that. - (c) AnT
Here it is this magic, straight from the (disgusting) Boost.Preprocessor.
#include <stdio.h> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/arithmetic/inc.hpp> #include <boost/preprocessor/comparison/not_equal.hpp> #include <boost/preprocessor/repetition/for.hpp> #include <boost/preprocessor/tuple/elem.hpp> #define MACRO_FOR_PRED(r, state) BOOST_PP_NOT_EQUAL( BOOST_PP_TUPLE_ELEM(3, 0, state), BOOST_PP_INC(BOOST_PP_TUPLE_ELEM(3, 1, state)) ) #define MACRO_FOR_OP(r, state) ( BOOST_PP_INC(BOOST_PP_TUPLE_ELEM(3, 0, state)), BOOST_PP_TUPLE_ELEM(3, 1, state), BOOST_PP_TUPLE_ELEM(3, 2, state) ) #define MACRO_FOR_MACRO(r, state) BOOST_PP_TUPLE_ELEM(3, 2, state) (BOOST_PP_TUPLE_ELEM(3, 0, state)) #define MACRO_FOR(from, to, macro) BOOST_PP_FOR((from, to, macro), MACRO_FOR_PRED, MACRO_FOR_OP, MACRO_FOR_MACRO) void func_0() {puts("func_0");} void func_1() {puts("func_1");} void func_2() {puts("func_2");} int main() { #define LOOP_BODY(x) BOOST_PP_CAT(func_,x), void (*array[])(void) = { MACRO_FOR(0, 2, LOOP_BODY) }; // 0 и 2 - номера первой и последней функции. #undef LOOP_BODY for (int i = 0; i < (sizeof array / sizeof array[0]); i++) array[i](); }
Run the code
(Redid the example from here .)
Minuses:
The number of functions is limited by the number of BOOST_PP_LIMIT_MAG
(256 by default; can be changed by regenerating library headers).
The numbers of the first and last functions in the array must be known at the compilation stage (preprocessing). They cannot even be placed in constant variables, only in macros.
Some slower compilation.