joepol
joepol

Reputation: 842

Why a function that has a return type but doesn't return anything doesn't fail compilation?

Consider the following example, compiled with g++ 5.4 (only):

#include <iostream>

int foo()
{
    std::cout << "foo" << std::endl;
}

int main()
{
    std::cout << foo();
    return 0;
}

foo() doesn't have any return statement, the code compiles and the function will return an unknown value, same will happen when return type is a pointer - which might cause a segmentation fault.

Why there is no error/warning when compiling such a function?

Is it because of the C++ standard or an issue to implement it?

Upvotes: 1

Views: 851

Answers (3)

eerorika
eerorika

Reputation: 238321

Why there is no error ... when compiling such a function?

Because the program is well-formed. Compilers are required to successfully compile all well-formed programs.

Why there is no ... warning when compiling such a function?

The standard does not require there to be a warning. Old versions of GCC only warn about mistakes like this if you ask the compiler to do so. GCC 8 enabled this particular warning by default.

and the function will return an unknown value

Not quite. The behaviour of the program is undefined if the execution reaches the end of the non-void function without a return, so that may or might not happen.

Note that the function would actually have well defined behaviour in case the stream insertion operator happened to throw or terminated the program. We know that stream insertion is not guaranteed to throw nor to terminate the program, and that it would actually be quite surprising. But the compiler cannot make that kind of generalisations.

Upvotes: 2

Ornob Rahman
Ornob Rahman

Reputation: 35

I'm using g++ 9.3.0, so can't tell much about g++ 5.4

At older versions, if you have a C++ program missing a return statement from a function that is supposed to return a value, g++ will compile it happily with no errors (or even a warning, unless -Wreturn-type or -Wall or -Werror=return-type is used). Trying to use the return value from the function will most likely cause a segmentation fault.

If you want that behavior, use -Werror=return-type

Upvotes: 0

Pete Becker
Pete Becker

Reputation: 76245

The language definition says that this produces undefined behavior. That's because it is sometimes not possible to diagnose it. Compilers that warn you about this kind of thing are occasionally wrong. I've added an unneeded return statement to silence one compiler, only to have another complain about that return statement as "unreachable code"

Upvotes: 4

Related Questions