Curious Case of f; Why Does it Always Print 1 in Output?
Encountering a peculiar behavior where calling a function without parentheses (f;) and printing its result with std::cout consistently yields the number 1 can raise questions. Initially, one might expect the code to print a function pointer, but observations indicate otherwise.
Delving into the code below:
#include
using namespace std;
void pr()
{
cout We can see that pr; does not technically call the pr() function. Instead, the function pointer is being passed to cout. When the function pointer is converted to a bool during this process, it behaves akin to a logical expression where a non-zero value evaluates to true. This translates to 1 when printed.
Furthermore, in pre-C 11 standard, there exists no overload that permits streaming a function pointer. This makes it challenging to format and print function pointers directly using std::cout. However, with the advent of C 11, one can define a custom overload to achieve this:
template
std::ostream & operatorEmploying this overload, cout
(func_ptr=)(num_args=0)
This custom overload demonstrates printing function pointers of varying arity. While it alleviates the issue for function pointers, it does not fully resolve scenarios involving overloaded functions or function templates where specifying the desired overload becomes essential.
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