Home >Backend Development >C++ >How Do I Print Function Pointers in C Using `cout` and `printf`?
Printing Function Pointers with cout and printf
In C , function pointers can be printed using cout or printf, but with different behavior depending on the format specifier used.
cout Operator
By default, cout treats function pointers as boolean values and prints 1 for non-null pointers and 0 for null pointers. To print the actual address, it must be explicitly cast to void*:
cout << (void *)pf;
printf Function
When using printf with the %p format specifier, function pointers are treated as pointers and their addresses are printed in hexadecimal:
printf("%p", pf);
Function Pointers as Booleans
Function pointers are indeed treated as booleans in C . This is due to the boolean conversion rule that allows pointers to be cast to bool, where a non-null pointer evaluates to true and a null pointer to false. This behavior can be unexpected if not taken into consideration.
Member Function Pointers
Printing member function pointers is more complex as they are not simple pointers. However, it is possible to print the address of the member function using a trick:
cout << (void *)(*(int **)&pf);
This takes advantage of the fact that the address of the member function is stored in the function pointer's second element, and casts it to void*.
The above is the detailed content of How Do I Print Function Pointers in C Using `cout` and `printf`?. For more information, please follow other related articles on the PHP Chinese website!