Logo Questions Linux Laravel Mysql Ubuntu Git Menu

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

like image 210
TheFuzz Avatar asked Feb 26 '23 17:02


2 Answers

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"


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.

like image 119
Prasoon Saurav Avatar answered Mar 05 '23 11:03

Prasoon Saurav

Here's the reason as to why you do not get error/warning as it is something which is known as Undefined Behavior (UB)

$6.6.3/2 - "Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function."

Unfortunately, a clean compilation with/without warning apart from any other imaginable behavior is all part of UB.

As @Prasoon mentioned, 'main' function is an exception to this rule.

like image 41
Chubsdad Avatar answered Mar 05 '23 13:03