c - right way to define pointer to the function -
everyone, have 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); // <- here ptr_foo = &foo; foo_for_foo(ptr_foo); return 0; }
does matter how define pointer function:
1) void (*ptr_foo); 2) void (*ptr_foo)(int, int);
my compiler receives both versions
thanks in advance explanations of difference
the 2 forms not equivalent.
void (*ptr_foo)
not function pointer @ all. it's normal, non-function void pointer. parentheses superfluous , misleading. it's if had written void* ptr_foo
.
void (*ptr_foo)(int, int)
proper way declare function pointer function taking 2 int
s , returning void
.
the reason works because in c, void
pointers implicitly convertible other type of pointer. is, can assign other pointer void*
, , can assign void*
other pointer.
but fact works in example accident of syntax. cannot in general replace void (*foo)(int, int)
void (*foo)
.
if try doing some_function
in argument list foo_for_foo
, compiler complain when try invoke some_function
because not function pointer.
similarly, if foo
function happened return int
instead of void
, notice problem right away. declaring ptr_foo
int (*ptr_foo)
have resulted in error on statement ptr_foo = &foo
because unlike void
pointers, int
pointers not implicitly convertible other pointer types.
in short, always use second form. 1 correct in general, despite fluky case.
Comments
Post a Comment