首頁 > 後端開發 > C++ > 主體

為什麼函數名稱相當於 C 中帶有位址運算子的函數指標?

Patricia Arquette
發布: 2024-11-15 07:27:02
原創
633 人瀏覽過

Why are Function Names Equivalent to Function Pointers with the Address-of Operator in C?

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板