On 12/20/12 1:53 PM, Rui Maciel wrote:
> wrote:
>
>> I have this:
>>
>> #include <iostream>
>>
>> int& foo() {}
>>
>> int main(void)
>> {
>> foo() = 1 + 1;
>>
>> std::cout << foo() << std::endl;
>>
>> return 0;
>> }
>>
>>
>> Compiling with gcc it works,
>> when executing the output is "2".
>>
>> What the hell is this and why this works?
>
> In C++, flowing off the end of a function is equivalent to a return with no
> value, and a return statement without an expression is only permitted in C++
> in functions that don't return a value. Therefore, although the standard
> states that this is behavior is undefined, it contradicts other behaviors
> defined in standard. Therefore, if it isn't treated as a bug, it should be.
>
>
> Rui Maciel
>
The issue is that in general, the compiler can not be always know if the
function can flow off the end of the function, as it requires solving
the halting problem, and the compiler may be missing key information to
even try it.
For example, should this be required to generate a diagnostic?
int foo() {
bar();
}
What if bar always calls exit()?, or throws?
Because of this problem, the standard should require a diagnostic for a
"possible" path from flowing off the end, and the committee probably
felt it wasn't worth trying to define a set of minimal cases that a
certain to do so (because it actually is fairly hard to do at the level
of rigor required by the standard).
Now it does turn out that many cases, like the one presented originally,
can often be detected by the compiler, and thus a "good" compiler will
issue a warning where it can detect that this is the likely case.