Function Name as Function Pointer: A Design Rationale
The equivalence between using a function name as a function pointer and applying the address-of operator to the function name is a curious language design.
Rationale
According to the ANSI C90 Rationale document, this equivalence was introduced to enhance the convenience of function pointers. By allowing function designators to be used interchangeably with pointers, developers gain the flexibility to call functions using shorthand notation or the more conventional pointer syntax.
Implicit Conversion
The language design also includes an implicit conversion between function types and function pointers when used as parameters. However, this conversion is not applicable when a function type is used as a return type. This behavior aims to prevent unintended pointer returns and ensure type safety.
Example
Consider the following code:
typedef bool (*FunType)(int); bool f(int); int main() { FunType a = f; // Equivalent to &f FunType *j(); // Returns function pointer }
In this example, the a variable can be assigned the function pointer for f without using the address-of operator. This shorthand syntax simplifies the code and makes it more readable.
Inconsistency with Arrays
While the equivalence between function names and function pointers is consistent with the way arrays are used in C, it does introduce some inconsistency. For instance, using the name of an array (a) as a pointer (&a) is not allowed, highlighting the special treatment given to functions in this regard.
Conclusion
The equivalence between function names and function pointers was introduced as a design decision to improve the convenience of using function pointers. While this approach provides flexibility, it also introduces some inconsistencies in the language's behavior.
The above is the detailed content of Why are Function Names Equivalent to Function Pointers in C?. For more information, please follow other related articles on the PHP Chinese website!