"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does Printing a Function Pointer Without Invocation Yield \"1\" in C++?

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

Published on 2024-11-14
Browse:139

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:

cout 

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:

template 
std::ostream & operator

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

cout 

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3