How can I compare function pointers in C++? Is it stable?
For example, would something like this be valid:
if(pFnc == &myFnc){
//Do something
}
How can I compare function pointers in C++? Is it stable?
For example, would something like this be valid:
if(pFnc == &myFnc){
//Do something
}
The == (equal to) and the != (not equal to) operators have the same semantic restrictions, conversions, and result type as the relational operators except for their lower precedence and truth-value result. [Note: a < b == c < d is true whenever a < b and c < d have the same truth-value. ] Pointers to objects or functions of the same type (after pointer conversions) can be compared for equality. Two pointers of the same type compare equal if and only if they are both null, both point to the same function, or both represent the same address (3.9.2).
Emphasis mine.
The function pointer is essentially a memory address like any other pointer in C++. So when comparing pointers you are always comparing memory addresses not values which means that it doesn't matter what those pointers point to as long as both pointers are of the same type.
Both pFnc
and myFnc
have to be defined. The correct comparison would be:
if(pFnc == myFnc)
{
//Do something
}