To complement GMan's answer here (x
is a function definition) as to why the 1
.
The reason for the output to be 1
is that at the place of call std::cout << x
, the function decays into a pointer to the function (the language does not allow you to pass functions as arguments to other functions, so as with arrays an implicit conversion to pointer-to is performed). Now, there is no overload of an ostream
that takes a function pointer, and the compiler tries to select a conversion to any of the available overloads. At that point it finds that the best conversion sequence is to bool
and it prints 1
(the pointer is not 0).
You can check this by changing the behavior, you can use std::cout << std::boolalpha << x
, and that will print true
instead of 1
. Also, it is interesting to note that VS is right with this one, as the expression std::cout << x
requires taking the address of x
, then the function is used and the program is ill-formed if there is no definition for that function. You can again check that by providing a definition:
int f() {}
int main() {
int x(int()); // 1
x( &f ); // 2
}
int x( int(*)() ) { // 3
std::cout << "In x" << std::endl;
}
Where I have manually performed the conversion from function
to pointer-to-function
in the definition of x
(1) and the call with the argument f
(2) --note that the declaration in 1 and the definition in 3 are the same signature, and that the &
in x( &f )
will be performed by the compiler if you don't do it.