How to work in a macro parameter before inserting a marker?

I have a function (ansi c) that is recursive in its definition. Thus, it looks like:

void function_2(int *value){
    /*this is the base function*/
}
void function_4(int *value){
    function_2(value);
    function_2(value);
    /*other operations*/
}
void function_8(int *value){
    function_4(value);
    function_4(value);
    /*other operations*/
}

      

Etc. To create these functions, I create macros, for example:

#define FUNCTION( m, h)\
void function_##m(int *value){\
    function_##h(value);\
    function_##h(value);\
    /*other operations\
};

      

And then I make my statements like this:

FUNCTION(4,2)
FUNCTION(8,4)

      

Note that the second parameter of the macro (h) is always half the first parameter of the macro (m). Is there any means so I can make a macro using just one parameter (m) and work with it, so when I concatenate it (using ##) I can use "m / 2" instead of h?

It should be something like:

function_##m/2(value);\

      

+3


source to share


1 answer


You cannot use compile time computation and token insertion like what you want to do. On the other hand, if you are the /*other operations*/

same and only the value m

changes, it is best to do m

in a parameter instead of using macros to define many functions.

You can do it like this:



void function(int m, int *value) {
    if ( m == 2 ) {
        /*run base code*/
    } else {
        function(m/2, value);
        function(m/2, value);
        /*other operations*/
    }
}

      

+1


source







All Articles