C function function call using the ternary operator

I have two C functions f1and f2that take the same arguments. Based on the condition, I need to call one or another argument with the same arguments:

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

I understand that you can use the syntax:

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

Is it possible to have DRY syntax that requires writing arguments at a time?

+4
source share
2 answers

Yes, it works just as well.

The function call operator ()just needs the left side, which calculates a pointer to the function, which names perform the functions.

deefence, () .

:

#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-ish. , .:)

+5

:

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

All Articles