C ++编译器-被遗忘的return语句 [英] C++ compiler - forgotten return statement

查看:112
本文介绍了C ++编译器-被遗忘的return语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的函数来返回要在屏幕上显示的字符串。

I wrote a simple function to return a string for me to display on the screen.

static std::string  myFun(int myId){
  std::ostringstream stream;
  int myStatus;
  if(get_status(&myStatus)) stream << get_error();
  else{
    stream << "my status:" << myStatus;
  }
    return stream.str();
}

代码本身可能并不重要。但是我以防万一。我遇到的问题是因为在我最初的尝试中,我忘了包含return语句

The code itself is probably not important. But I include it just in case.The problem I encountered is because in my original attempt, I forget to include the return statement

return stream.str();

编译器编译时没有错误,但运行时却没有错误。该程序不断获取消息,例如

The compiler compiled with no error, but when I run it. The program keep getting messages like

Aborted(core dumped)

我很奇怪,我搜索了stackoverflow并安装了valgrind和所有东西。然后检查代码,我意识到我只是忘了包含return语句!我希望编译器会注意到这些错误。

I freak out and I search I stackoverflow and installed valgrind and everything. Then I check the code, I realize I simply forget to include the return statement! I would expect the compiler to notice these kinds of mistake.

有人可以向我解释为什么编译器无法检测到错误吗?

Can someone explain to me why the compiler cannot detect the error?

推荐答案

在非<$$的所有控制路径上没有 return 值的代码的行为c $ c> void 函数为未定义。 (C ++有许多未定义的构造;也许是出于对开发人员的偏爱而不是对开发人员的最大性能和可移植性的考虑。)

The behaviour of code that doesn't have a return value on all control paths of a non-void function is undefined. (C++ has plenty of undefined constructs; perhaps a consequence of favouring maximum performance and portability over kindness to developers.)

好的编译器会警告您,甚至会提供您可以设置将警告(以及其他警告)升级为错误。请查阅您的编译器文档。

A good compiler will warn you of this and will even provide you settings to upgrade that warning (along with others) to an error. Consult your compiler documentation.

这篇关于C ++编译器-被遗忘的return语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆