How can I compare function pointers in C++? Is it stable?
For example, would something like this be valid:
if(pFnc == &myFnc){
//Do something
}
Two function pointers can be compared with the == and != operators, just like any other kind of pointers. We can also compare a function pointer to the NULL pointer using the == and != operators.
Yes, it is fine. The C standard is pretty self-explanatory in this case (C11 6.3.
We can compare pointers if they are pointing to the same array. Relational pointers can be used to compare two pointers. Pointers can't be multiplied or divided.
Originally Answered: What is the difference between pointer to function and function pointer? A function pointer points to the memory address, where the function's code is stored. So unlike other functions function pointer points to code rather than data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With