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

enr*_*cis 6 c syntax function call function-call

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

if (condition) {
    result = f1(a, b, c);
} else {
    result = f2(a, b, c);
}
Run Code Online (Sandbox Code Playgroud)

我理解可以使用以下语法:

result = condition ? f1(a, b, c) : f2(a, b, c)
Run Code Online (Sandbox Code Playgroud)

是否有可能需要一次写入参数的DRY语法?

unw*_*ind 7

是的,它就像你建议的那样工作正常.

函数调用操作符()只需要一个评估函数指针的左侧,函数的名称就是这样.

调用时无需对函数指针进行derefence,()运算符就是这样做的.

此示例程序演示:

#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;
}
Run Code Online (Sandbox Code Playgroud)

它打印:

0 -> -1
1 -> 2
2 -> 1
3 -> 4
4 -> 3
5 -> 6
6 -> 5
7 -> 8
8 -> 7
9 -> 10
Run Code Online (Sandbox Code Playgroud)

这里没什么奇怪的.

而且由于C在Python之前有点过时,也许它的Python语义在这里是C-ish.当然,或者只是理智.:)