Re:How Do I Declare a Function Pointer in C?
by bstamour on Thursday January 19, 2017 @02:23PM
(#13438680)
This is one of those cases where I prefer C++
and now declarations are a bit more sane:
[ Parent
| on HN ]
Re:How Do I Declare a Function Pointer in C?
by david-given on Thursday January 19, 2017 @02:31PM
(#13438743)
In C, the easiest thing to do is to just use a typedef. You get to use the same syntax as for normal function calls with no trying to remember where that blasted extra * goes, and typically end up with cleaner code anyway.
typedef void function_ptr_t(int i);
function_ptr_t* ptr;
Re:How Do I Declare a Function Pointer in C?
by bstamour on Thursday January 19, 2017 @02:43PM
(#13438849)
Yeah, typedefs solve the problem for fixed types. I guess you could use a macro to create a generic FUNC_PTR or something as well.
Re:How Do I Declare a Function Pointer in C?
by ramshorns on Thursday January 19, 2017 @05:19PM
(#13439986)
Macros are often a bad idea for defining types. If you do
#define INT_PTR int*
INT_PTR p, q;
the code is actively misleading. Is there a better way to do it for function pointers?
Re:How Do I Declare a Function Pointer in C?
by flukus on Thursday January 19, 2017 @05:52PM
(#13440219)
There are a few other problems with multiple declarations aren't there? I though they were discouraged in c.
Re:How Do I Declare a Function Pointer in C?
by Const-me on Thursday January 19, 2017 @02:43PM
(#13438847)
In C++, pointers to member functions are even more cumbersome than C function pointers.
Re:How Do I Declare a Function Pointer in C?
by kllrnohj on Thursday January 19, 2017 @04:00PM
(#13439443)
auto greet = std::mem_fn(&Foo::display_greeting);
Looks pretty simple to me, much simpler than C function pointers. :)Pairs nicely with std::bind, too, like so:
Foo foo;
std::function<void(int)> setter = std::bind(&Foo::setValue, &foo, std::placeholders::_1);
setter(42);
Re:How Do I Declare a Function Pointer in C?
by Const-me on Thursday January 19, 2017 @05:48PM
(#13440184)
If you need to keep that pointer in a collection, or in a class member, or pass as a function argument, “auto” won’t work.
And std::function introduce some performance overhead.
Re:How Do I Declare a Function Pointer in C?
by kllrnohj on Thursday January 19, 2017 @07:50PM
(#13440882)
> If you need to keep that pointer in a collection, or in a class member, or pass as a function argument, “auto” won’t work.
Trivially solved with decltype, no need to remember anything.
decltype(std::mem_fn(&Foo::Whatever))
Typedef it if you want.
> And std::function introduce some performance overhead.
It's the same performance as a virtual function call. Pretty much the same as a function pointer invoke.
Re:How Do I Declare a Function Pointer in C?
by Koshkin on Friday January 20, 2017 @10:11AM
(#13444311)
Indeed, C++ is an excellent language, extremely writable; but readable, it isn't.