Search code examples
cfor-loopfunction-calls

Looping operations


I would like to write something like this;

for (op1 in (plus, minus, times, divby, exponent)) {
    printf("%d", a op1 b);
}

so that what actually ends up being executed is something like this

printf("%d", a + b);
printf("%d", a - b);
printf("%d", a * b);
printf("%d", a / b);
printf("%d", a ^ b);

How can I write this?


Solution

  • Array of function pointers would do.

    double plus(int a, int b);
    double minus(int a, int b);
    double times(int a, int b);
    double divby(int a, int b);
    double exponent(int a, int b);
    
    typedef double (*p_fun)(int a, int b);
    
    int main()
    {
        int a = 5, b = 10;
        p_fun pa[] = {plus, minus, times, divby, exponent};
        for( int i = 0; i < sizeof(pa)/sizeof(p_fun); i++ )
        {
            printf("%f\n", pa[i](a, b));
        }
        return 0;
    }