Printing a Function Pointer Without Invocation
When attempting to print a function without parentheses (i.e., as f instead of f()), one may encounter unexpected results such as always printing the value 1. This seemingly paradoxical behavior stems from the underlying mechanism involved.
In the provided code, the statement cout << pr; does not actually invoke the function pr. Instead, it passes the function pointer pr to cout. C implicitly interprets this pointer as a bool value, with a non-null pointer evaluating to true and hence printing as 1.
In order to print the function pointer itself, one must explicit cast it to a void* pointer. This can be achieved by using expressions like cout << (void*)pr.
C 11 and Function Pointer Overloading
With the advent of C 11, a more convenient method to print function pointers emerged. Overloading the << operator for function pointers allows for more informative output. For instance, one can define an overload that prints the function's address and arity (number of arguments):
<code class="cpp">template <class RType, class ... ArgTypes> std::ostream & operator<<(std::ostream & s, RType(*func)(ArgTypes...)) { return s << "(func_ptr=" << (void*)func << ")(num_args=" << sizeof...(ArgTypes) << ")"; }
This overload will print output in the format (func_ptr=
) (num_args=The above is the detailed content of How to Print a Function Pointer in C Without Invoking It?. For more information, please follow other related articles on the PHP Chinese website!