The compiler does not complain about a function that does not return a 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 fine, but shouldn't the compiler complain about the lack of a return statement?

EDIT 0: GNU g ++ compiler

+3
source share
2 answers

Try compiling with the -Wall(gcc) [ -Wreturn-type] option . You will receive a warning that “Control reaches the end of the non-void function” or something like “no return statement in the function returning the 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 return value of a non-boolean function (without a return statement) Undefined Behavior.

+5
source

, /, , Undefined Behavior (UB)

$6.6.3/2 - " ; Undefined ."

, / , , UB.

@Prasoon, "main" .

+1

Source: https://habr.com/ru/post/1777155/


All Articles