Why Does "cout a function without calling it (not f() but f;). Print 1 Always?"
In this code, the code tries to "call" a function named pr without using parentheses. However, this is not actually calling the function. Instead, it is passing the function pointer to the cout function. When the function pointer is implicitly converted to a bool value, it is evaluated as true. Since true is equivalent to 1 in C , the output is always 1.
To clarify, the following lines from the provided code are not invoking the pr function:
<code class="cpp">pr; cout << pr; // output: 1 cout << *pr; // output: 1 (dereferencing the function pointer, which is still true) cout << ≺ // output: 1 (address of the function, which is a non-zero value)</code>
To truly call the pr function, you would need to use parentheses like pr().
This behavior stems from the fact that function pointers are implicitly convertible to bool. In C 11, it is possible to overload the operator<< for function pointers to provide a more informative output. However, this would still not work for overloaded functions or function templates without explicitly specifying the desired overload (usually through a cast).
The above is the detailed content of Why Does \'cout\' Print \'1\' When a Function Pointer is Used Without Parentheses?. For more information, please follow other related articles on the PHP Chinese website!