1

I want to pass a function into another function, but I have confused myself so much over the syntax and what is actually happening. This is the code I am running:

#include <stdio.h>

int func(int a){
    printf("%d\n", a);
}

void another_func(int p_func(int)){
int (*funcptr)(int) = p_func;
funcptr(7);
}

int main(void){

    another_func(func);

    return 0;
}

However, I have found out that I can put how many asterix I want before func when calling it in main, for example:

another_func(*******************func);

I can do the same when assigning the function to the function pointer, for example:

int (*funcptr)(int) = ***********p_func;

I am though forbidden to put an ampersand in front of p_func when assigning it to the function pointer. Also it doesn't seem to matter if I write:

void another_func(int (*p_func)(int)){

Can my plead for help wake some of the legendary C gods from their slumber who can make a detailed explanation? I really don't get how this works, what is passed etc.

Donkey King
  • 87
  • 1
  • 8

2 Answers2

2

According to the C Standard (6.3.2.1 Lvalues, arrays, and function designators)

4 A function designator is an expression that has function type. Except when it is the operand of the sizeof operator65) or the unary & operator, a function designator with type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to function returning type’

On the other hand (6.5.3.2 Address and indirection operators)

4 The unary * operator denotes indirection. If the operand points to a function, the result is a function designator;

Thus you can place as many asterisks before a function designator as the compiler will allow according to its own limits.:)

And you may use operator & with a function designator. For example

#include <stdio.h>

int f( int x )
{
    return x;
}

int main(void) 
{
    int ( *fp )( int ) = &f;

    printf( "%d\n", fp( 10 ) );

    return 0;
}

Take into account that a function parameter declared as a function is adjusted to pointer to the function type.

Thus these two function declarations declare the same one function and can be both present in a compilation unit (though the function shall be defined once if it is not inline)

void another_func(int p_func(int));
void another_func(int ( *p_func )(int));
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

"I have found out that I can put how many asterix I want before func when calling it in main." I don't want to offend you, but I suggest you to read something about pointers. An example about what you're looking for could be:

int foo(int (*foo2)(void))
{
    foo2();
}

int foo2(void)
{
    return rand();
}

int main(void)
{
    foo(foo2);
}
Modfoo
  • 97
  • 9
  • There are tons of things written about pointers. Elaborate what you mean that I don't understand about pointers. – Donkey King Jan 18 '17 at 00:02