Friday, July 31, 2009

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 %26lt;iostream%26gt;





bool my_func()


{


return false;


}





int main()


{


if (bool my_func())


std::cout %26lt;%26lt; "true\n";


else


std::cout %26lt;%26lt; "false";


return 0;


}





the output is "true".


Using Microsoft Visual C++ version 6.0

Can you explain surprising C++ parsing?
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.
Reply: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.


No comments:

Post a Comment