bingfeng wrote:
hello,
anyone else can explain why following codes give wrong result while
compiler accept it still?
int & foo() {}
int main()
{
int x = foo;
std::cout << x << std::endl;
}
After including the missing headers, I still get an error:
invalid conversion from 'int& (*)()' to 'int'
So changing
int x = foo;
to
int x = foo();
I get a clean compile but undefined behavior, e.g., as per [6.6.3/2].
As for _why_ the standard specifies undefined behavior for falling through
the end of a function that has to return something, one has to recall that
it is generally undecidable which paths of a function can be taken for
possible input values. In the most common cases, it is easy but still a
burden on the compiler that the C++ standard does not wish to impose.
Best
Kai-Uwe Bux