Search code examples
cfunction-pointersvariadic-functions

Is it possible that variadic function takes function pointer as argument?


The title says it all. Can function be passed as argument in variadic function and if so, how can I access it?

#include <stdio.h>
#include <stdarg.h>
#include <math.h>

void func(double x, int n, ...){
    va_list fs;
    va_start(fs, n);

    for (int i = 0; i < n; i++)
    {
        va_arg(fs, *); //this is where I get confused
    }
    
}

int main(){
    double x = 60.0 * M_PI / 180.0;
    func(x, 3, &cos, &sin, &exp);

}

Solution

  • The second argument to va_args is the type to convert to. In this case each function has compatible types, specifically they take a single double as an argument and return a double. The type of a pointer to such a function is double (*)(double), so that it what you would use for the type.

    double (*f)(double) = va_arg(fs, double (*)(double));
    double result = f(x);
    

    Also, don't forget to call va_end(fs); after the loop.