【问题标题】:Is there a way to use a variable piece of code in a function?有没有办法在函数中使用可变代码段?
【发布时间】:2021-12-31 07:39:10
【问题描述】:

最近我正在(用 C 语言)编程,我意识到如果我可以编写自己的循环函数,我的代码会更简单。所以我需要在不同的时间运行一段代码(这段代码在整个程序中是不同的),但我不知道如何在我的函数中将一段代码作为参数。

例如,以 for(){"X"} 循环为例,它的输出可能会因“X”而异,因此我们可以以某种方式将“X”作为函数中的参数。

虽然我在没有定义新函数的情况下解决了代码中的问题,但它导致了一个更普遍的问题,我无法在网上找到答案:有没有办法在函数中使用可变代码段? (和 for() 一样)

编辑:这是我在网上找到的similar problem。但是我的问题比这个更笼统。

【问题讨论】:

  • 不确定您的意思,但我认为您正在寻找的是一些 if 语句调用您的 for 循环中的相关函数?
  • 请举例说明您拥有的代码并告诉您什么是疼痛

标签: c function


【解决方案1】:

您可以将代码放入函数中并将函数(作为指针)传递给其他函数(或在循环中使用),如下所示:

#include<stdio.h>


static int add(int a, int b)
{
    return a + b;
}

static int multiply(int a, int b)
{
    return a * b;
}

/*  The third argument to g, f, is a pointer to a function that takes two int
    parameters and returns an int.
*/
static void g(int a, int b, int (*f)(int a, int b), const char *name)
{
    //  This uses the pointer f to call the function.
    printf("The %s of %d and %d is %d.\n", name, a, b, f(a, b));
}

int main(void)
{
    //  These pass the function add or multiply to g.
    g(3, 4, add, "sum");
    g(3, 4, multiply, "product");
}

C 在这方面没有很大的灵活性。所涉及的函数应该大多具有相同的签名(采用相同类型的参数并具有相同的返回类型)。有一些可用的灵活性,使用可变参数列表或通过转换为不同的函数类型,但是,当使用指向函数的指针时,您通常应该寻求统一的签名。

【讨论】:

    猜你喜欢
    • 2016-06-05
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多