c - 如何将函数的定义传递给其他函数,以便其他函数在 C 语言中调用它?

标签 c function c-preprocessor

我有一些#define,它们定义了一个函数,我想将一些定义传递给函数“ff”,所以它会调用它,下面是示例:

#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;
}

有可能做到这一点吗?

最佳答案

#define 未定义函数。它定义了 macro .

宏在程序文本编译之前展开。宏扩展通过用宏体替换宏来修改程序文本。编译后的代码中没有任何内容对应于宏定义。

您可以将函数作为参数传递(或者,更准确地说,您可以传递指向函数的指针)。但这些函数必须实际存在于可执行文件中。 (不一定在源代码中:指向库函数的指针完全没问题。)由于宏不存在,因此不存在指向宏的指针,并且在程序执行期间它们不能用于任何目的。

关于c - 如何将函数的定义传递给其他函数,以便其他函数在 C 语言中调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54601834/

相关文章:

c - gdb 不会在断点处停止

c - 从C中的文件读取

Python Numpy nan_to_num 帮助

C++ else 语句仅当宏被定义时

c链表从txt文件读取

Codeforce 问题 474 A 中给出运行时错误的代码

python - If 语句 - 这是一个字符串吗?

swift - 在 Swift 中将具有多个参数的函数作为闭包传递

C 翻译阶段 4

c - #define, #ifdef#undef#endif