Function as a parameter to function

I just noticed that this compiles without any errors or warnings using -pedantic -Wall with gcc and clang .

 #include <stdio.h> int x = 0; void func(int f(const char *)) { f("func()!"); } int main(void) { func(puts); } 

It seems that in this case the parameter f treated as a pointer to the int (*)(const char *) function.

But this is a behavior that I have never seen or heard of. Is this legal C code? And if so, what happens when you have a function as a parameter to a function?

+5
source share
1 answer

This is permitted by standard. From the standard C99 chapter 6.9.1 (taken from http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf ):

EXAMPLE 2 To transfer one function to another, we can say

 int f(void); /*...*/ g(f); 

Then the definition of g can read

 void g(int (*funcp)(void)) { /*...*/ (*funcp)(); /* or funcp(); ... */ } 

or, equivalently,

 void g(int func(void)) { /*...*/ func(); /* or (*func)(); ... */ } 
+2
source

Source: https://habr.com/ru/post/1258587/


All Articles