简体   繁体   中英

How to pass a define of function to other function, so the other function will call it in C-language?

I have a few #define, that define a functions and I want to pass some define to function "ff", so it will call it, here is the example:

#define square(x) x*x
#define add(a,b) a+b
#define subtract(a,b,c) a-b-c
#include <stdio.h>

int ff(my_func)
{
    //do something useful
    my_func; //this should call square or add or subtract
    //do something useful
}

int main()
{
   printf("Square is %d \n",square(3)); //this works fine
   printf("Add is %d \n", add(7, 8)); //this works fine
   printf("Subtract is %d \n", subtract(21, 1, 8)); //this works fine

   ff(square(10)); //this doesn't work, or it can be ff(add(5, 5));

   return 0;
}

Is it even possible to do this ?

#define does not define a function. It defines a macro .

Macros are expanded before the program text is compiled. A macro expansion modifies the program text by substituting the macro with the macro body. Nothing in the compiled code corresponds to a macro definition.

You can pass functions as arguments (or, more accurately, you can pass pointers to functions). But these functions must actually exist in the executable. (Not necessarily in the source code: pointers to library functions are perfectly fine.) Since macros do not exist, there is no such thing as a pointer to a macro, and they cannot be used fir any purpose during program execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM