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

时间:2010-11-27 06:38:15

标签: 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()

这个编译完全正常,但是编译器不应该抱怨缺少return语句吗?

编辑0:GNU g ++编译器

2 个答案:

答案 0 :(得分: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>

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

答案 1 :(得分:1)

这就是为什么你没有得到错误/警告的原因,因为它被称为未定义行为(UB)

  

$ 6.6.3 / 2 - “流出一个结尾   功能相当于一个回报   没有价值; 这会导致   一个未定义的行为   价值回归功能。

不幸的是,除了任何其他可以想象的行为之外,带有/不带警告的干净编译都是UB的一部分。

正如@Prasoon所提到的,'main'函数是此规则的一个例外。