Correct syntax to store function pointer
Asked Answered
P

1

17

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));
}
Piave answered 25/5, 2020 at 16:52 Comment(4)
function decays to pointer.Proclitic
Similar question.Tiertza
Worth mentioning that for a pointer-to-member-function, only the syntax &ClassName::functionname will work.Clevelandclevenger
Guess what: xxx = &&&&g<float> also works. And when you call through that pointer you can write (*xxx)(5) or (**xxx)(5) or even (******xxx)(5).Saurel
H
14

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,

  1. For xxx = g<float>;, function-to-pointer implicit conversion is performed from g<float>, the converted pointer is assigned to xxx.

  2. For xxx = &g<float>;, operator& is used explicitly to take the address of the function, the returned pointer is assigned to xxx.

  3. 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.

Heraclitean answered 25/5, 2020 at 16:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.