Home >Backend Development >C++ >Why Does Printing a Function Pointer Without Invocation Yield \'1\' in C ?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 07:37:29206browse

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

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>

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>

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!

Statement:
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