C++ compiler - forgotten return statement

2019-07-05 04:59发布

问题:

I wrote a simple function to return a string for me to display on the screen.

static std::string  myFun(int myId){
  std::ostringstream stream;
  int myStatus;
  if(get_status(&myStatus)) stream << get_error();
  else{
    stream << "my status:" << myStatus;
  }
    return stream.str();
}

The code itself is probably not important. But I include it just in case.The problem I encountered is because in my original attempt, I forget to include the return statement

return stream.str();

The compiler compiled with no error, but when I run it. The program keep getting messages like

Aborted(core dumped)

I freak out and I search I stackoverflow and installed valgrind and everything. Then I check the code, I realize I simply forget to include the return statement! I would expect the compiler to notice these kinds of mistake.

Can someone explain to me why the compiler cannot detect the error?

回答1:

The behaviour of code that doesn't have a return value on all control paths of a non-void function is undefined. (C++ has plenty of undefined constructs; perhaps a consequence of favouring maximum performance and portability over kindness to developers.)

A good compiler will warn you of this and will even provide you settings to upgrade that warning (along with others) to an error. Consult your compiler documentation.



回答2:

Because, in the general case, it's not possible for the compiler to prove that your function doesn't return. What if it always throws an exception, instead, but that exception comes from a function defined in another translation unit e.g. a linked library?

Thus the language standard cannot require compilers to error out; thus, they don't bother.

However, in simple examples like this, the compiler can tell and, when it can, it will warn you. If you turn warnings on. Which you should do now.

Ultimately, though, in C++, spotting this kind of thing is the programmer's responsibility. Static analysis tools can help you to avoid such mistakes if you find your eyesight insufficient. :)