Can you explain surprising C++ parsing?

Much to my surprise, an incorrect copy and paste seems to be legal C++.

Instead of writing
if (my_func())
I accidentally wrote
if (bool my_func())

It seems to compare the function address. Can someone please explain this? I didn't think a function declaration could appear in an expression.

#include <iostream>

bool my_func()
{
return false;
}

int main()
{
if (bool my_func())
std::cout << "true\n";
else
std::cout << "false";
return 0;
}

the output is "true".
Using Microsoft Visual C++ version 6.0

soa2007-12-12T13:57:32Z

Favorite Answer

I don't think the code you showed is legal, since it didn't compile with gcc 4.2.0. Also it failed to compile with llvm.

http://llvm.org/demo/index.cgi

Probably it's a bug in microsoft's compiler.

Anonymous2007-12-12T09:45:52Z

Wow - that is interesting. I think what is happening is that the expression 'bool my_func()' is being evaluated to "true" because the function is working properly - in other words, it seems like, by including the function in the 'if' condition, it is basically checking to see if the return from it is valid, which - even though it is 'false' - is valid.