Why is Function Name Equivalent to Function Pointer with Address-of Operator?
In C programming, using a function name as a function pointer is equivalent to applying the address-of operator (&) to the function name. This seeming inconsistency with other language elements, such as arrays, has a specific rationale.
Rationale of Function Name Equivalence
According to the ANSI C90 Rationale document, the equivalence between function designators (function names) and function pointers was introduced to enhance convenience. By allowing both notations, the language provides a shorthand way to call member functions in packaged structures. For instance:
graphics.open(file) // Equivalent to (*graphics.open)(file)
Curiosities of Function Designators
This equivalence leads to peculiar but valid syntactical forms:
( &f)(); f(); (*f)(); (**f)(); (***f)(); pf(); (*pf)(); (**pf)(); (***pf)();
The Committee reasoned that prohibiting forms like (f)() while allowing a (for int a[]) would have been unnecessary and inconvenient.
Exceptions in Parameter and Return Types
Interestingly, a function type can be implicitly converted to a pointer to itself as a parameter (e.g., void g(FunctionType)). However, it cannot be converted to a pointer when used as a return type (e.g., FunctionType h();). This distinction ensures that function type compatibility issues are avoided.
以上是為什麼函數名稱相當於 C 中帶有位址運算子的函數指標?的詳細內容。更多資訊請關注PHP中文網其他相關文章!