未检查C ++ return语句

时间:2017-10-18 08:01:34

标签: c++ function compilation return compiler-warnings

Linux下的g ++ 5.4.1(UBUNTU 16.04)将编译以下内容 程序没有错误或警告:

#include <iostream>

std::string foo(){
    int a= 1;
    a++;
}

int main(){
    std::cout << foo();
    return 0;
}

显然,缺少“foo()”中的return语句和程序 在我的计算机核心转储中。我问自己为什么缺席了 在编译时甚至没有警告return语句?我错过了吗 什么?

2 个答案:

答案 0 :(得分:2)

我怀疑你没有启用警告编译。

像这样编译:

g++ -Wall -Wextra main.cpp

你应该得到:

  

警告:函数返回非void [-Wreturn-type]

时没有return语句

PS:这与GCC的版本无关。

编译器不必生成诊断消息,这就是为什么必须启用警告标志才能让编译器抱怨的原因。阅读Why does this C++ snippet compile (non-void function does not return a value)中的更多内容。

答案 1 :(得分:1)

您没有包含相应的警告标志。你可能只使用过这样的东西:

g++ source.cpp

添加: -Wall-pedantic-Wextra和类似的标记:

g++ -std=c++14 -Wall -Wextra -pedantic source.cpp

Live example
话虽如此,您还应该包含<string>标题:

#include <string>

并且不依赖于来自<iostream>免费字符串游戏