int& foo() {} works well?

B

bingfeng

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;
}

thanks!
 
K

Kai-Uwe Bux

bingfeng said:
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
 
B

bingfeng

Thanks, Pete and Kai, I was misled to check how initialiate a
reference in standard text found nothing of course. Common used g++
(3.4.5) and MSVC compiler keep silence on this both.
Sorry for my typo in original post, Kai.

bingfeng wrote:
After including the missing headers, I still get an error:
invalid conversion from 'int& (*)()' to 'int'
So changing
int x = foo;

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.

In addition, most compilers will give a warning on something as simple
as the code above. So they'll find the obvious problems, but not the
subtle ones.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,140
Latest member
SweetcalmCBDreview
Top