Search code examples
cfunction-pointersimplicit-conversionfunction-declaration

How to declare function pointer parameter


What is the difference between these 2 declarations:

double math_operation(double x, double (*func)(double));
double math_operation(double x, double func(double));

They both seem to work with the same exact call in GCC:

math_operation(2.0, sqrt);

Is it just syntactic sugar or is there more to it?


Solution

  • These two function declarations

    double math_operation(double x, double (*func)(double));
    double math_operation(double x, double func(double));
    

    declare the same one function. You may include the both declarations in your program though the compiler can issue a message that there are redundant declarations.

    The compiler implicitly adjusts a parameter having a function type to parameter of pointer type to the function.

    On the other hand, a function designator used as an argument is converted to pointer to the function.

    [Note: in general all these function declarations declare the same one function

    double math_operation( double, double (*)( double ) );
    double math_operation( double, double( double ) );
    double math_operation( const double, double (*)( double ) );
    double math_operation( const double, double( double ) );
    double math_operation( double, double (*)( const double ) );
    double math_operation( double, double( const double ) );
    double math_operation( const double, double (*)( const double ) );
    double math_operation( const double, double( const double ) );
    

    Also the pointer to the function itself can have the qualifier const

    double math_operation( double, double ( * const )( double ) );
    double math_operation( const double, double ( * const )( double ) );
    double math_operation( double, double ( * const )( const double ) );
    double math_operation( const double, double ( * const )( const double ) );
    

    -end note.]

    From the C Standard (6.7.6.3 Function declarators (including prototypes))

    8 A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1.