使用三元运算符的 C 函数调用选择

C function call selection using ternary operator

我有两个采用相同参数的 C 函数 f1f2。根据条件,我需要使用相同的参数调用一个或另一个:

if (condition) {
    result = f1(a, b, c);
} else {
    result = f2(a, b, c);
}

我知道可以使用语法:

result = condition ? f1(a, b, c) : f2(a, b, c)

是否可以使用 DRY 语法,要求一次写入参数?

可以像这样使用函数指针:

int (*f)(int, int, int, ...);
f = condition ? f1 : f2;
result = (*f)(a, b, c, ...);

是的,正如您建议的那样,它工作正常。

函数调用运算符 () 只需要一个计算结果为函数指针的左侧,函数名称就是这样做的。

调用时不需要取消引用函数指针,() 运算符会这样做。

此示例程序演示:

#include <stdio.h>

static int foo(int x) {
    return x + 1;
}

static int bar(int x) {
    return x - 1;
}

int main(void) {
    for (int i = 0; i < 10; ++i)
        printf("%d -> %d\n", i, (i & 1 ? foo : bar)(i));
    return 0;
}

它打印:

0 -> -1
1 -> 2
2 -> 1
3 -> 4
4 -> 3
5 -> 6
6 -> 5
7 -> 8
8 -> 7
9 -> 10

这里没有什么奇怪的。

并且由于 C 在 Python 之前相当早,所以这里可能是 Python 的语义是 C 风格的。当然,或者只是单纯的理智。 :)