c++ - 编译器不会提示函数没有返回值

标签 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++ 编译器

最佳答案

尝试使用 -Wall 选项进行编译 (gcc)[ -Wreturn-type 更精确]。您会收到类似“控制到达非 void 函数的末尾”或类似“返回非 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>

使用非 void 函数(没有 return 语句)的返回值是未定义的行为。

关于c++ - 编译器不会提示函数没有返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4290473/

相关文章:

c++ - 结构 DIR 的前向声明

c - 总线错误 - 这段代码有什么问题?

assembly - MIPS vs Intel x86 vs LLVM是第一种要学习的汇编语言?

c++ - 编译器不编译以下行 (C++)

c - ‘...’ token 之前的预期声明说明符或 ‘&’

c++ - CLion 重命名头文件

c++ - 在 CPP 中运行 tensorflow 模型

c++ - Boost函数指针多线程之谜

c++ - Visual Studio 还是 GCC?

java - 包不存在?