Home >Backend Development >C++ >Why does `std::cout
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:
<code class="cpp">#include <iostream> using namespace std; void pr() { cout << "sth"; } int main() { pr; cout << pr; // output: 1 cout << *pr; // output: 1 cout << ≺ // output: 1 }
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:
<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) << ")"; }
Employing this overload, cout << pr will now print:
<code class="text">(func_ptr=<address of pr>)(num_args=0)</code>
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.
The above is the detailed content of Why does `std::cout. For more information, please follow other related articles on the PHP Chinese website!