Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function as parameter to function [duplicate]

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?

like image 958
wefwefa3 Avatar asked Oct 30 '22 18:10

wefwefa3


1 Answers

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)(); ... */
}
like image 156
dkolmakov Avatar answered Nov 15 '22 06:11

dkolmakov