c++compiler-errorsreturng++

compiler doesn't complain about function not returning value


I have the following function:

bool Server::ServerInit()
{
//  bool listenResult = socket.Listen( (const uint8 *)_LOCAL_HOST, m_iPort );
//  if( true == listenResult )
//      cout << "Server passive socket listening\n";
//  else
//      cout << "Server passive socket not listening\n";
//      
//  return listenResult;
} // ServerInit()

this compiles perfectly fine, but shouldn't the compiler be complaining about the absence of a return statement?

EDIT 0: GNU g++ compiler


Solution

  • Try compiling with -Wall option (gcc)[ -Wreturn-type to be more precise]. You'll a get a warning something like "Control reaches end of a non-void function" or something like "no return statement in function returning non-void"

    Example:

    C:\Users\SUPER USER\Desktop>type no_return.cpp
    #include <iostream>
    int func(){}
    
    int main()
    {
       int z = func();
       std::cout<< z; //Undefined Behaviour
    }
    C:\Users\SUPER USER\Desktop>g++ -Wall no_return.cpp
    no_return.cpp: In function 'int func()':
    no_return.cpp:2:12: warning: no return statement in function returning non-void
    
    C:\Users\SUPER USER\Desktop>
    

    Using the returned value of a non-void function (having no return statement) is Undefined Behaviour.