Comparison of Pointers for Object Equivalence
When comparing pointers that refer to the same variable, as in the example:
int *a = something; int *b = something;
The question arises as to whether the equality operator "a == b" provides the expected result.
Equality Operator (==, !=)
According to the C standard, pointers of the same type can be compared for equality as follows:
Relational Operators (<, >, <=, >=)
Relational operators for pointers are defined only for pointers to objects or functions of the same type. The result depends on whether the pointers point to the same object or function, or whether one or both are null.
For example, in the case of an array, pointers to different elements compare greater or less than each other based on their position in the array. However, comparing pointers to non-array objects or functions that are not members of the same object may yield unspecified results.
Exceptions for Virtual Functions
In cases where either pointer points to a virtual member function, the comparison result is unspecified by the standard.
Comparison in Practice
It should be noted that the comparison of pointers using the equality operator (==, !=) is generally well-defined and reliable for determining if pointers point to the same object. However, relational operators (<, >, <=, >=) should be used with caution, as their behavior can be different depending on the specific context.
Bonus: Comparison with Templates
The standard library also provides templates for pointer comparison, such as std::less<> and friends. These templates guarantee a total order for any pointer type, even when the built-in operators do not provide well-defined behavior.
The above is the detailed content of When Comparing Pointers in C , How Reliable Are the Equality and Relational Operators?. For more information, please follow other related articles on the PHP Chinese website!