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);
}
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With