Function Name Equivalence to Function Pointers
Function names in C serve as both function designators and function pointers, providing a convenient shorthand for referencing functions. This equivalence has been debated, and its rationale lies in historical considerations and the desire to simplify function pointer usage.
The C90 Rationale document explains that function designators can be used in multiple forms, including as function calls (both with and without the asterisk operator) and as function pointers. This flexibility allows for various syntactical constructions, some of which may seem unusual.
For example, consider the following declarations:
int f(); int (*pf)();
Here, the function name f can be called as f(), *f(), or even ***f(). Additionally, the function pointer pf can be called in similar ways, such as pf(), *pf(), or **pf().
The rationale for this equivalence stems from the desire to simplify the use of function pointers. In many cases, it is more convenient to use the function name directly as a function pointer rather than having to manually apply the address-of operator (&). Therefore, the language allows the equivalence of function names and function pointers.
However, this equivalence is limited to certain contexts. When returning a function type, the function type itself cannot be implicitly converted to a pointer to itself. This is illustrated in the example below:
typedef bool FunctionType(int); FunctionType h(); // Error!
In this case, h() is declared as a function that returns a function type, but this cannot be implicitly converted to a pointer to that function type. However, when used as a parameter, the function type can be implicitly converted to a pointer to itself.
FunctionType g(FunctionType); // Implicitly converted to void g(FunctionType *)
This implicit conversion simplifies the passing of function pointers as parameters. Overall, the equivalence of function names and function pointers is a design choice that balances convenience with contextual restrictions, making it a practical feature in C programming.
The above is the detailed content of Why are Function Names and Function Pointers Equivalent in C ?. For more information, please follow other related articles on the PHP Chinese website!