编译器不会抱怨函数没有返回值

The*_*uzz 4 c++ compiler-construction compiler-errors return

我有以下功能:

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()
Run Code Online (Sandbox Code Playgroud)

编译完全没问题,但编译器是否应该抱怨没有返回语句?

编辑0:GNU g ++编译器

Pra*_*rav 7

尝试使用-Wall选项(gcc)进行编译[ -Wreturn-type更准确].你会得到一个警告,例如"控制到达非空函数的结尾"或类似"函数返回非空虚中的无返回语句"

例:

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>
Run Code Online (Sandbox Code Playgroud)

使用非void函数的返回值(没有return语句)是Undefined Behavior.

  • 你需要"-Wall",而不是"-wall"; 命令行选项区分大小写.请注意," - w"是"​​禁止所有警告消息". (2认同)