Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a Function Many Times - (Passing a Function as a Parameter) – C

Tags:

c

So the code below can be used to pass a function as a parameter:

void printNumber(int nbr)
{
    printf("%d\n", nbr);
}

void myFunction(void (*f)(int))
{
    for(int i = 0; i < 5; i++)
    {
        (*f)(i);
    }
}

int main(void)
{
    myFunction(printNumber);
    return (0);
}

But how can I change that code so that the integer for “printNumber” is defined outside of “myFunction”? In other words I only want to call the function “myFunction” for x number of times with the same integer .

I wrote some pseudocode to explain what I'm trying to accomplish:

void printNumber(int nbr)
{
    printf("%d\n", nbr);
}

void myFunction(void (*f)(*int)) //pseudocode
{
    for(int i = 0; i < 5; i++)
    {
        (*f)(*int); //pseudocode
    }
}

int main(void)
{
    myFunction(printNumber(5)); //pseudocode
    return (0);
}
like image 635
Sigrid Avatar asked Dec 22 '19 21:12

Sigrid


2 Answers

printnumber(5) means to call printnumber immediately and pass it 5. You want to pass printnumber and 5 separately as two arguments

void printNumber(int nbr)
{
    printf("%d\n", nbr);
}

// void (*f)(int) is a pointer to a function that takes an int
// arg is the int to pass in
void myFunction(void (*f)(int), int arg)
{
    for(int i = 0; i < 5; i++)
    {
        // call f and pass in arg
        (*f)(arg);
    }
}

int main(void)
{
    // pass the function and the arg to use
    myFunction(printNumber, 5);
    return (0);
}
like image 85
Lou Franco Avatar answered Sep 30 '22 01:09

Lou Franco


You need another argument.

void printNumber(int nbr)
{
    printf("%d\n", nbr);
}

void myFunction(void (*f)(int), int Arg)
{
    for(int i = 0; i < 5; i++)
    {
        (*f)(Arg);
    }
}

int main(void)
{
    myFunction(printNumber, 42);
    return (0);
}

The parameter declaration void (*f)(int) only says that the function pointed to by f expects an int. It doesn't mean that an int is also packed into the function pointer somehow.

like image 26
PSkocik Avatar answered Sep 30 '22 03:09

PSkocik