Home > Backend Development > C++ > body text

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

Patricia Arquette
Release: 2024-11-15 07:27:02
Original
632 people have browsed it

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)
Copy after login

Curiosities of Function Designators

This equivalence leads to peculiar but valid syntactical forms:

( &f)(); f(); (*f)(); (**f)(); (***f)();
pf(); (*pf)(); (**pf)(); (***pf)();
Copy after login

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.

The above is the detailed content of Why are Function Names Equivalent to Function Pointers with the Address-of Operator in C?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template