C ++ compiler - the forgotten return statement

I wrote a simple function to return a string for 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 probably doesn't matter. But I turn it on just in case. The problem I am facing is that in my original attempt I forgot to include the return statement

return stream.str();

      

The compiler compiled without error, but when I run it. The program continues to receive messages like

Aborted(core dumped)

      

I'm losing my temper and I've searched stackoverflow and installed valgrind and all. Then I inspect the code, I realize I am just forgetting to include the return statement! I expected the compiler to notice such errors.

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

+3


source to share


2 answers


The behavior of code that doesn't matter return

in all control paths of a non function void

is undefined. (C ++ has many undefined constructs, possibly a consequence of developers' preference for maximum performance and portability.)



A good compiler will warn you about this and even provide you with settings to update this warning (along with others) to an error. Check your compiler's documentation.

+7


source


Because, in general, it is impossible for the compiler to prove that your function is not returning. What if it always throws an exception, but this exception comes from a function defined in another translation system, for example. linked library?

Thus, a locale cannot ask for errors from compilers; thus, they do not bother.



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

Ultimately, however, in C ++, it is the responsibility of the programmer to define this type. Static analysis tools can help you avoid such errors if you find that your vision is insufficient. :)

+2


source







All Articles