Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a macro as an argument in a C function?

I want to pass a macro as an argument in a C function, and I don't know if it possible. I would like to see this operation, for instance:

I have these macros:

#define PRODUCT(A, B) ((A) * (B)) 
#define SUM(A, B) ((A) + (B))

And then I have this function with the following signature:

int just_a_function(int x, MACRO_AS_PARAMATER_HERE);

and then i want to call this function like:

just_a_function(10, SUM);

is it possible?

Thanks

like image 809
Anderson Carniel Avatar asked Feb 08 '14 23:02

Anderson Carniel


1 Answers

You can't pass as function argument.

But if function is a macro this is possible.

#include <stdio.h>

#define PRODUCT(A, B) ((A) * (B)) 
#define SUM(A, B) ((A) + (B))
#define JUST_A_FUNCTION(A, B, MACRO) MACRO(A, B)

int main() {
        int value;

        value = JUST_A_FUNCTION(10, 10, SUM);
        printf("%d\n", value);

        value = JUST_A_FUNCTION(10, 10, PRODUCT);
        printf("%d\n", value);

        return 0;
}
like image 80
TheOliverDenis Avatar answered Nov 14 '22 23:11

TheOliverDenis