Why do function pointer definitions work with any number of ampersands '&' or asterisks '*'?

前端 未结 3 656
失恋的感觉
失恋的感觉 2020-11-21 23:21

Why do the following work?

void foo() {
    cout << \"Foo to you too!\\n\";
};

int main() {
    void (*p1_foo)() = foo;
    void (*p2_foo)() = *foo;
          


        
3条回答
  •  情歌与酒
    2020-11-22 00:28

    & and * are idempotent operations on a symbol declared as a function in C which means func == *func == &func == *&func and therefore *func == **func

    It means that the type int () is the same as int (*)() as a function parameter and a defined func can be passed as *func, func or &func. (&func)() is the same as func(). Godbolt link.

    A function is really an address, therefore * and & have no meaning, and instead of producing an error, the compiler chooses to interpret it as the address of func.

    & on a symbol declared as a function pointer however will get the address of the pointer (because it now has a separate purpose), whereas funcp and *funcp will be identical

提交回复
热议问题