2

Possible Duplicate:
Why can you return from a non-void function without returning a value without producing a compiler error?

Consider the real code:

std::ostream &operator << (std::ostream &stream, const sqc_var &var)
{
    switch (var.type()) 
    {
        case sqc_var::type_number:
            return stream << var.as_number();
        case sqc_var::type_string:
            return stream << var.as_string();
        case sqc_var::type_object:
            stream << "{";
            for (auto &child : var.children())
            {
                stream << child.name() << ": " << child.value() << " "; // <-- crash there
            }
            stream <<  " }";
    }

    //// return stream; <-- originaly no return was there.
}

This code will crash program if var have an type_object type after first recursive call of operator << because it returns nothing when the reference to std::ostream expected.

Clang 3.1 even does not print warning.

Modern GCC and MSVC print warning but compile it.

Why C++ compiler allows such erroneous code?

Also I'll be glad to see any references to C++ standard which allows such code or explanation when it can be usefull.

Community
  • 1
  • 1
inkooboo
  • 2,904
  • 1
  • 19
  • 24
  • Can you provide a complete example, so that we can reproduce the error locally? – Björn Pollex Aug 07 '12 at 09:37
  • In general, it's impossible to tell whether the end of a function is unreachable. So the only sensible options are to force the programmer to always provide a `return` even if it should never be reached; or to allow the programmer to omit it, risking undefined behaviour if it ever is reached. The latter is more consistent with the vague C/C++ philosophy of only paying for what you need. – Mike Seymour Aug 07 '12 at 09:54

0 Answers0