Home > Backend Development > C++ > body text

How to Print a Function Pointer in C Without Invoking It?

Mary-Kate Olsen
Release: 2024-10-25 07:33:29
Original
912 people have browsed it

How to Print a Function Pointer in C   Without Invoking It?

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 &amp; operator<<(std::ostream &amp; s, RType(*func)(ArgTypes...))
{
    return s << "(func_ptr=" << (void*)func << ")(num_args=" 
              << sizeof...(ArgTypes) << ")";
}
Copy after login

This overload will print output in the format (func_ptr=

) (num_args=).
By employing this overload, one can obtain more detailed information about a function pointer when printing it using cout.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!