【问题标题】:How to pass a define of function to other function, so the other function will call it in C-language?如何将函数的定义传递给其他函数,以便其他函数用 C 语言调用它?
【发布时间】:2019-02-08 23:58:59
【问题描述】:

我有几个#define,定义了一个函数,我想将一些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;
}

甚至有可能做到这一点吗?

【问题讨论】:

  • 不完全 :( 在 C 语言中,您通常传递 function pointer。查看链接以获取解释和示例。如果您有任何具体问题,请回复。

标签: c function c-preprocessor


【解决方案1】:

#define 没有定义函数。它定义了一个macro

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

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

【讨论】:

    猜你喜欢
    • 2014-06-04
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    相关资源
    最近更新 更多