I came across on a strange behavior of the following code, while playing around with initialization of ints using g++ 4.4.3.
int main()
{
int x(int());
int y = int();
cout << x << " " << y << endl;
}
the result is:
1 0
The value of “y” is 0 as expected, but the value of x is strangely “1”!
On VS2008 yields the following link error (a function declaration, but without definition):
unresolved external symbol "int __cdecl x(int (__cdecl*)(void))"
Can anyone explain this strange behavior of g++?
To complement GMan’s answer here (
xis a function definition) as to why the1.The reason for the output to be
1is that at the place of callstd::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 anostreamthat 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 tobooland it prints1(the pointer is not 0).You can check this by changing the behavior, you can use
std::cout << std::boolalpha << x, and that will printtrueinstead of1. Also, it is interesting to note that VS is right with this one, as the expressionstd::cout << xrequires taking the address ofx, 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:Where I have manually performed the conversion from
functiontopointer-to-functionin the definition ofx(1) and the call with the argumentf(2) –note that the declaration in 1 and the definition in 3 are the same signature, and that the&inx( &f )will be performed by the compiler if you don’t do it.