Isma
Isma

Reputation: 127

how to operate in a macro parameter before token pasting?

I've a function (ansi c) that is recursive in its definition. Thus, it is in the form:

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*/
}

And so on. To create these functions, I'm creating macros, such as:

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

And then I make their declarations as follows:

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

Notice that the second macro parameter (h) is always half the value of the first macro parameter (m). Is there any means so I can make the macro using only one parameter (m) and than operate with it so when I concatenate it (using ##) I can use "m/2" instead of h?

It should be something as:

function_##m/2(value);\

Upvotes: 3

Views: 101

Answers (1)

Jay Bosamiya
Jay Bosamiya

Reputation: 3209

You cannot use compile time calculation and token pasting like what you want to do. On the other hand, if you /*other operations*/ are same and only the value of m is changing, it might be best to make m into a parameter instead of using macros to define many functions.

You could make it similar to the following:

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

Upvotes: 1

Related Questions