Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

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

2 Answers

Relevance
  • 1 decade ago
    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.

  • Anonymous
    1 decade ago

    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.

Still have questions? Get your answers by asking now.