The correct way to define a function pointer

Everyone, I have this piece of code:

void foo(int var, int var1)
{
 printf("%d\n", var);
 printf("%d\n", var1);
}

void foo_for_foo( void (*some_function)(int, int))
{
 int x = 5;
 some_function(x, x);
}

int main()
{
 void (*ptr_foo);  // <- look here
 ptr_foo = &foo;
 foo_for_foo(ptr_foo);

 return 0;
}

it matters how to define a function pointer:

1) void (*ptr_foo);
2) void (*ptr_foo)(int, int);

my compiler gets both versions

in advance for clarifying the difference

+3
source share
2 answers

Two forms are not equivalent.

void (*ptr_foo)not a pointer to everything. This is a normal, invalid void pointer. Brackets are redundant and misleading. It is exactly as if you wrote void* ptr_foo.

void (*ptr_foo)(int, int)is the correct way to declare a pointer to a function with two intand return void.

, , , C, void . void*, void* .

, , . void (*foo)(int, int) void (*foo).

some_function foo_for_foo, some_function, .

, foo int void, . ptr_foo int (*ptr_foo) ptr_foo = &foo, void int .

, . , , .

+6

void (*ptr_foo); void *. ptr_foo = &foo; foo_for_foo. gcc -Wall ( - , ), .

0

Source: https://habr.com/ru/post/1767075/


All Articles