这个 C++ 代码如何在没有结束返回语句的情况下编译? [英] How does this C++ code compile without an end return statement?

查看:35
本文介绍了这个 C++ 代码如何在没有结束返回语句的情况下编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下编译良好的代码(使用 Visual Studio 2005):

I came across the following code that compiles fine (using Visual Studio 2005):

SomeObject SomeClass::getSomeThing()
{
    for each (SomeObject something in someMemberCollection)
    {
        if ( something.data == 0 )
        {
            return something;
        }
    }
    // No return statement here
}

如果方法末尾没有 return 语句,为什么会编译?

Why does this compile if there is no return statement at the end of the method?

推荐答案

这是为了支持与 C 的向后兼容性,C 并不严格要求从所有函数返回.在这些情况下,您只剩下返回位置(堆栈或寄存器)中的最后一个值.

This is to support backwards compatibility with C which did not strictly require a return from all functions. In those cases you were simply left with whatever the last value in the return position (stack or register).

如果这是在没有警告的情况下编译的,尽管您可能没有将错误级别设置得足够高.大多数编译器现在都会对此发出警告.

If this is compiling without warning though you likely don't have your error level set high enough. Most compilers will warn about this now.

这篇关于这个 C++ 代码如何在没有结束返回语句的情况下编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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