c - What is the difference between defining a function type and a function pointer type? -
as know, can define function type:
typedef void (fn)(void);
and can define function pointer type:
typedef void (*pfn)(void);
there 2 functions. first function's parameter type function, , other function pointer:
void a(fn fn1) { fn1(); } void b(pfn fn1) { fn1(); }
i implement function callback:
void callback(void) { printf("hello\n"); }
and pass argument , b:
int main(void) { a(callback); b(callback); return 0; }
both , b work well, , print "hello"
.
so want know difference between defining function type , function pointer type? or actually, same?
given abuse can use function pointers (&func
, func
, *func
, **func
, … end same value function func
), there few practical differences between two. can use fn *
indicate pointer function, not trivial transform.
however, here's mild adaptation of code, using non-parameter variable of type pfn
, attempting (unsuccessfully) use non-parameter variable of type fn
. not compile, there difference when used @ file scope (global) or local scope , not in parameter list.
pfn.c
typedef void (fn)(void); typedef void (*pfn)(void); static void callback(void) { printf("hello\n"); } static void a(fn fn1) { fn fn2 = callback; fn *fn3 = callback; fn1(); fn2(); (*fn2)(); fn3(); (*fn3)(); } static void b(pfn fn1) { pfn fn2 = callback; fn1(); fn2(); } int main(void) { a(callback); b(callback); return 0; }
compilation
$ gcc -g -o3 -std=c99 -wall -wextra -wmissing-prototypes -wstrict-prototypes \ > -werror pfn.c -o pfn pfn.c: in function ‘a’: pfn.c:13:5: error: function ‘fn2’ initialized variable fn fn2 = callback; ^ pfn.c:13:8: error: nested function ‘fn2’ declared never defined fn fn2 = callback; ^ $
Comments
Post a Comment