Printing Function Pointers with cout
In C , printing function pointers directly using cout can be problematic. Instead, it is advisable to convert the function pointer to void* before printing it. This is demonstrated in the following code snippet:
#include <iostream> using namespace std; int foo() {return 0;} int main() { int (*pf)(); pf = foo; cout << "cout << pf is " << pf << endl; cout << "cout << (void *)pf is " << (void *)pf << endl; printf("printf(\"%p\", pf) is %p\n", pf); return 0; }
Output:
cout << pf is 1 cout << (void *)pf is 0x100000b0c printf("%p", pf) is 0x100000b0c
As seen above, cout implicitly converts the function pointer to bool, resulting in the output 1. To print the actual address of the function, it must be cast to void*.
Function pointers of type void* can be printed directly using cout. This is because void* is a generic pointer type that can hold the address of any type, including function pointers.
Observing Member Function Pointers
Printing member function pointers using void* does not work due to their more complex structure. However, according to the C Standard, rvalues of function pointers can be converted to bool.
The above is the detailed content of How Can I Correctly Print Function Pointers in C using `cout`?. For more information, please follow other related articles on the PHP Chinese website!