Home >Backend Development >C++ >Can Distinct C Functions Have the Same Address?
Function Pointer Equality and Function Coalescing
Question:
Can distinct functions have the same address? For instance, are &foo and &bar guaranteed to be unequal, and &foo
Answer:
The C standard allows implementations to optimize functions with identical definitions and coalesce them into a single function. This means the addresses of two such functions may not be distinct.
Standard Compliance:
Defect report 1400 on function pointer equality acknowledges this optimization but suggests that it is not clear whether the standard needs to address it explicitly. The response from the committee states that implementations are free to optimize within the constraints of the "as-if" rule.
"As-If" Rule:
Under the "as-if" rule, an implementation can emulate observable behavior without adhering to specific implementation details. Since addresses of functions are not explicitly required to be distinct, this optimization does not violate the rule.
Equality Operators:
According to section 5.10 of the standard, two pointers compare equal if they are both null, point to the same function, or represent the same address. This allows implementations to assign the same address to two functions if they have identical definitions.
Observations:
Keith Thompson notes that printing the result of &foo == &bar is observable behavior. Changing the observable behavior by coalescing functions could potentially break such programs.
Additionally, macros like SIG_DFL and SIG_ERR in
Inter-Procedural Optimization:
Jan Hubička, a GCC developer, confirms that folding identical functions to the same address is non-conforming behavior. It breaks certain parts of GCC's precompiled headers code that rely on address comparisons.
Conclusion:
While the standard does not explicitly prohibit the optimization of coalescing identical functions, it is important to consider the potential impact on code that relies on function addresses being distinct. Implementations should approach this optimization with caution and avoid it in cases where observable behavior would be affected.
The above is the detailed content of Can Distinct C Functions Have the Same Address?. For more information, please follow other related articles on the PHP Chinese website!