I just noticed that this compiles without any errors or warnings using -pedantic -Wall
with both gcc
and clang
.
#include <stdio.h>
int x = 0;
void func(int f(const char *)) {
f("func()!");
}
int main(void) {
func(puts);
}
It appears that the parameter f
is treated like pointer to function int (*)(const char *)
in this case.
But this a behavior that I have never seen or heard anything about. Is this legal C code? And if so then what happens when you have a function as a parameter to a function?
It is allowed by the standard. From C99 standard chapter 6.9.1 (took from http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf):
EXAMPLE 2 To pass one function to another, one might say
int f(void); /*...*/ g(f);
Then the definition of g might read
void g(int (*funcp)(void)) { /*...*/ (*funcp)(); /* or funcp(); ... */ }
or, equivalently,
void g(int func(void)) { /*...*/ func(); /* or (*func)(); ... */ }
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