【问题标题】:compiler doesn't complain about function not returning value编译器不会抱怨函数没有返回值
【发布时间】:2010-11-27 06:38:14
【问题描述】:

我有以下功能:

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()

这编译得很好,但是编译器不应该抱怨没有返回语句吗?

编辑 0:GNU g++ 编译器

【问题讨论】:

  • 你用的是什么编译器?我用 C4716 大声抱怨你的代码 sn-p 的 Visual C++ 编译器。
  • @TheFuzz:我的抱怨声也相当响亮!
  • 我进行了编辑。我正在使用 gnu g++ 编译器
  • @TheFuzz:事实上 g++ 默认不会抱怨。令人惊讶...
  • 为什么没有设置为 g++ 的默认设置?

标签: c++ compiler-construction compiler-errors return


【解决方案1】:

尝试使用-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语句)的返回值是未定义行为。

【讨论】:

  • -Wall 被列为我的编译器当前使用的选项之一。它仍然没有抱怨。
  • 你需要“-Wall”,而不是“-wall”;命令行选项区分大小写。注意“-w”是“禁止所有警告信息”。
  • @TheFuzz 当我使用 -Wall 时得到以下信息:“test.cpp:在成员函数'bool Server::ServerInit()'中:test.cpp:14:警告:控制到达结束非空函数”
【解决方案2】:

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

$6.6.3/2 - “从结尾流出 函数等价于返回 没有价值; 这会导致 a中未定义的行为 值返回函数。"

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

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

【讨论】:

  • 另外补充一点,main() 是这个规则的一个例外。 :)
猜你喜欢
  • 2020-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-09
  • 2019-04-25
  • 2011-01-08
  • 2012-09-12
  • 1970-01-01
相关资源
最近更新 更多