Is it possible to pass a function pointer as a const argument?
I get the following gcc error:
warning: type defaults to 'int' in declaration of 'f' [-Wimplicit-int] void execute(void (const *f)(void));
...when compiling this code:
#include <stdio.h>
void print(void);
void execute(void (const *f)(void));
int main(void)
{
execute(print); // sends address of print
return 0;
}
void print(void)
{
printf("const!");
}
void execute(void (const *f)(void)) // receive address of print
{
f();
}
This is not a duplicate of What is meaning of a pointer to a constant function?, which addresses pointers to const functions as opposed to a const
function argument.
Pointers can be declared as pointing to mutable (non-const) data or pointer to constant data. Pointers can be defined to point to a function. My coworkers and I were discussing the use of "const" with pointers and the question came up regarding the use of const with function pointers.
Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points. When you use pass-by-pointer, a copy of the pointer is passed to the function.
We can create a pointer to a constant in C, which means that the pointer would point to a constant variable (created using const). We can also create a constant pointer to a constant in C, which means that neither the value of the pointer nor the value of the variable pointed to by the pointer would change.
Pointer argument to functionWe can also pass the pointer variable to function. In other words, we can pass the address of a variable to the function instead of variable value.
The syntax you want is:
void execute(void (* const f)(void));
This says that f
is a const
pointer to a function that takes no arguments ((void)
is a special syntax for no arguments) and returns nothing (void
). A const
on the right side of an *
says that the pointer is const
. A const
on the left side says the pointer points to something that is const
.
The fact that it is a const
pointer means that you will not change f
(assign a new value) in the function, and the compiler should give you an error if you do (unless the change is hidden from it, which it can be by casts). It does not say anything about the function itself—the function pointed to is not const
in any sense because the parameter is const
.
When you wrote:
void execute(void (const * f)(void));
the const
on the left side of the *
means that the pointer was pointing to something that was const
, rather than that the pointer itself was const
. Since it was saying the pointer was pointing to something there and you did not list a specific type, the compiler warned you that the type was missing (and defaulted to int
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With