#include <stdio.h>
typedef int (*func_t)(int);
int foo(int x) {
return x * 2;
}
int main() {
const func_t ptr = foo; // Works
//const func_t *ptr = &foo; // Fails: why?
printf("%d\n", ptr(5)); // Outputs 10
}
Issue:
The line const func_t ptr = foo; works fine.
However, uncommenting const func_t *ptr = &foo; results in a compilation error
error: invalid conversion from 'int (*)(int)' to 'const func_t*' {aka 'int (* const)(int)'}
Why does const func_t *ptr = &foo; fail, and how can I fix it?
constthat causes the trouble; it's the extra layer of pointer, plus the fact that&functionproduces the same value as justfunction.aka 'int (* const*)(int). "How can I fix it?" This depends on what you want to do, especially why you want a pointer to a function pointer, which is not something that commonly needed.const func_t *ptr = &foo;is valid in C, but its behavior may vary depending on the compiler implementation and settings. My compiler (gcc 13.2.0, clang 17.0.6, target x86_64-unknown-linux-gnu ) gives incompatible pointer type warning but still compiles.const func_t*is an object pointer type, but&foois a function pointer type. The C standard does not say you can convert between these two. In fact they may not even be of the same size. See stackoverflow.com/a/4810460/3966456