gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:42:06 24 4
gpt4 key购买 nike

我有一些#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com