Reputation:
Surprisingly, the following code compiles well both in gcc and clang no matter what symbol before function name is used: *
, &
or nothing. Does standard allow any of them? What is preferred way to store function pointers?
#include <stdio.h>
typedef int foo(int a);
template <typename X>
int g(int y) {
return y * sizeof(X);
}
int main() {
foo* xxx;
// 1. what is correct according to standard?
// 2. why they all work?
xxx = *g<float>;
xxx = &g<float>;
xxx = g<float>;
printf("ok %d\n", xxx(5));
}
Upvotes: 17
Views: 593
Reputation: 172924
All should work fine and have the same effect here. Which one is preferred is a style-issue, IMO the 1st one in your code is confusing, the other two are quite common usages.
I'll explain in the reverse order of your code for convenience,
For xxx = g<float>;
, function-to-pointer implicit conversion is performed from g<float>
, the converted pointer is assigned to xxx
.
For xxx = &g<float>;
, operator&
is used explicitly to take the address of the function, the returned pointer is assigned to xxx
.
For xxx = *g<float>;
, function-to-pointer implicit conversion is performed from g<float>
, then the pointer is dereferenced by operator*
, which returns a function reference, on which function-to-pointer implicit conversion is performed (again), the converted pointer is assigned to xxx
at last.
Upvotes: 14