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?
Function pointers in C need to be declared with an asterisk symbol and function parameters (same as function they will point to) before using them in the program. Declaration of function pointers in C includes return type and data type of different function arguments.
The following is the syntax for the declaration of a function pointer: int (*FuncPtr) (int,int);
The Basic syntax of function pointers We can think of function pointers like normal C++ functions. Where void is the function's return type. *fun_ptr is a pointer to a function that takes one int argument. It's as if we are declaring a function called *fun_ptr which takes int and returns void .
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.
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