Home >Backend Development >C++ >Do Distinct C Functions Always Have Distinct Function Pointer Addresses?
Function Pointer Equality and Distinct Addresses
Question:
In C , are function pointers for distinct functions guaranteed to have distinct addresses? Specifically, for the following code:
void foo() {} void bar() {} template<class T> void foo() { }
Are &foo != &bar and &foo
Answer:
The standard does not explicitly require function pointers for distinct functions to have distinct addresses. However, it does allow implementations to optimize functions with identical definitions, and this optimization can result in identical function addresses.
In fact, Microsoft Visual C (MSVC) aggressively folds functions with identical implementations, assigning them the same address. This behavior is considered non-conforming.
On the other hand, the Gold linker offers a safer setting that maintains distinct addresses for functions, even if they have identical definitions.
Detailed Explanation:
The C standard defines equality for function pointers as follows:
The latter condition gives latitude for implementations to alias different functions and does not explicitly require pointers to different functions to be unequal.
However, taking the address of a function is observable behavior, and changing the address can violate the "as-if" rule. This rule requires that the implementation's behavior be indistinguishable from the behavior specified in the standard.
Therefore, while the standard does not explicitly prohibit function address aliasing, it can be argued that it violates the "as-if" rule, leading to non-conforming behavior.
Observations:
Conclusion:
While the standard allows for function address aliasing, it is generally recommended to avoid this optimization as it can create portability and reliability issues.
The above is the detailed content of Do Distinct C Functions Always Have Distinct Function Pointer Addresses?. For more information, please follow other related articles on the PHP Chinese website!