Home > Software engineering >  Is there a way to use a variable piece of code in a function?
Is there a way to use a variable piece of code in a function?

Time:11-22

Lately I was programming (in C) and I realized that my code would be simpler if I could write my own loop function. So I needed to run a piece of code different times(the pieces of code vary throughout the program) but I have no idea how to take a piece of code as an argument in my function.

For instance, take the for(){"X"} loop, its output may vary depending on "X", so we could somehow refer to "X" as an argument in the function.

Although I solved the problem in my code without defining the new function, it led to a more general problem which I couldn't find its answer online: Is there a way to use a variable piece of code in a function? (in the same manner that for() does)

Edit: Here is a similar problem that I found online. However my question is more generalized than this one.

CodePudding user response:

You can put code in functions and pass a function (as a pointer) to other functions (or use it in a loop), like this:

#include<stdio.h>


static int add(int a, int b)
{
    return a   b;
}

static int multiply(int a, int b)
{
    return a * b;
}

/*  The third argument to g, f, is a pointer to a function that takes two int
    parameters and returns an int.
*/
static void g(int a, int b, int (*f)(int a, int b), const char *name)
{
    //  This uses the pointer f to call the function.
    printf("The %s of %d and %d is %d.\n", name, a, b, f(a, b));
}

int main(void)
{
    //  These pass the function add or multiply to g.
    g(3, 4, add, "sum");
    g(3, 4, multiply, "product");
}

C does not have a lot of flexibility about this. The functions involved should mostly have the same signature (take the same types of parameters and have the same return type). There is some flexibility available, using variable argument lists or by casting to different function types, but, when using pointers to functions, you should generally seek a uniform signature.

  • Related