Ayush Pandey Ayush Pandey - 1 year ago 45
C Question

Passing inputs to a function from a list of inputs without hard-coding it in C

Suppose I have a function:

void add(int a, int b , int c);

and I have an array which contains 3 integer values:

int L[] = {1,2,3};

Now I want to pass these values to add without writing

I mean is there a way of creating a Single input from multiple inputs and passing it to the function which will treat that single input as multiple inputs ??.

Answer Source

If you mean something like Python

def foo(a, b, c):
    return a + b + c

x = (1, 2, 3)
print(foo(*x)) # the '*' does the magic of calling foo with 1, 2, 3

then this is not possible in portable C.

What you can do is change the interface of foo to accept an array of arguments, e.g.

int sum(int *data, int n) {
    int tot = 0;
    for (int i=0; i<n; i++) {
        tot += data[i];
    return tot;

can call it with

int x[] = {10, 20, 30, 40};
int res = sum(x, 4);

If you cannot change the function definitions and you have many of them with the same signature what you can do is use function pointers to factor out the call:

int sum3(int a, int b, int c) {
    return a+b+c;

int mul3(int a, int b, int c) {
    return a*b*c;

int call_int_int3(int(*f)(int, int, int), int* args) {
    return f(args[0], args[1], args[2]);

int data[] = {10, 20, 30};
int sum = call_int_int3(sum3, data);
int prod = call_int_int3(mul3, data);

but you will need a different wrapper for each distinct signature (number and type of arguments and type of return value).