Home > Backend Development > C++ > body text

Why Does Printing a Function Pointer Without Invocation Yield \'1\' in C ?

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

Why Does Printing a Function Pointer Without Invocation Yield

Printing a Function Pointer Without Invocation: Understanding the Mysterious Output of 1

In an intriguing code snippet, a function is "called" without invoking its parentheses ("pr;") and then printed using std::cout. Surprisingly, the result consistently yields 1, defying expectations.

The Enigma of Constant 1s

The code calls the function pr three different ways:

<code class="cpp">cout << pr;  // output: 1
cout << *pr; // output: 1
cout << &pr; // output: 1
Copy after login

Intuition suggests that a function pointer should be printed instead of the enigmatic 1s. However, understanding this behavior requires delving deeper into C 's type conversion mechanisms.

Type Conversion and Bool Values

When passed as an argument to cout, pr is implicitly converted to a bool. This conversion occurs because bool is a fundamental type, and cout requires a fundamental type as input. In C , a converted bool value is true if the original value is nonzero and false if it is zero.

Since pr is a function pointer, its value is a non-zero memory address. Consequently, when converted to bool, it evaluates to true, which is output as 1 by cout.

Customizing Function Pointer Printing (C 11 onwards)

C 11 introduces a customizable overload that allows for more informative printing of function pointers:

<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) << ")";
}</code>
Copy after login

This overload prints the function pointer's address and the number of arguments it takes. It can be used to print pr as follows:

<code class="cpp">cout << pr; // output: (func_ptr=0x12345678)(num_args=0)</code>
Copy after login

This approach provides more descriptive output, making it easier to understand the function pointer's properties.

The above is the detailed content of Why Does Printing a Function Pointer Without Invocation Yield \'1\' in C ?. 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!