Search code examples
cfunctionsyntaxcallfunction-call

C function call selection using ternary operator


I have two C functions f1 and f2 that take the same arguments. Based on a condition, I need to invoke one or the other one with the same arguments:

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

I understand it is possible to use the syntax:

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

Is it be possible to have a DRY syntax that requires to write arguments a single time?


Solution

  • Yes, it works fine just like you suggested.

    The function call operator () just needs a left-hand-side that evaluates to a function pointer, which names of functions do.

    There's no need to derefence function pointers when calling, the () operator does that.

    This sample program demonstrates:

    #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;
    }
    

    It prints:

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

    There is nothing strange here.

    And since C predates Python by a fair bit, perhaps it's Python's semantics that are C-ish here. Or just plain sane, of course. :)