当函数最后缺少 return 语句时,为什么它会起作用? [英] Why does it work when a function missing a return statement at the end?

查看:24
本文介绍了当函数最后缺少 return 语句时,为什么它会起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 C++.下面的代码让我很困惑:

I'm learning C++. The codes below confused me:

int test_return(int a)
{
    for (int i = 40; i < 44; i++)
    {
        if (i == a)
        {
            cout << "return here with i: " << i << endl;
            return 59;
        }
    }
}

int main()
{
    cout << "in main: " << test_return(61) << endl;
    return 0;
}

我知道我在函数 test_return 的末尾缺少返回语句.

I know I'm missing a return statement at the end of function test_return.

但是编译器说没有错误,并且在执行时可以正常工作.

But the compiler says no error and it works when executed.

所以我选择了一些特定的数字,例如 40,44,59,61 看看是哪一个test_return 函数会选择返回.

So I pick up some particular numbers like 40,44,59,61 to see which one the function test_return will choose to return.

我试了几次,输出总是这样:

I tried several times, the output is always this:

in main: 44

似乎函数 test_return 在 for 语句结束之前返回了 int i.

It seems like that the function test_return returned the int i before the for-statement ended.

我的问题是:

这合法吗?

它是如何工作的?

更新:

我将这些代码添加到函数 test_return 的末尾:

I add these codes at the end of function test_return:

int i = 100;
int square = i * i;

出来了:

in main: 10000

感谢莫斯科的@Vlad 回答!有帮助.

Thanks for @Vlad from Moscow's answer! It helps.

推荐答案

如果有 Intel 兼容的计算机,那么该函数似乎在寄存器 EAX 中返回结果.

If there is an Intel-compatible computer then it seems the function returns the result in register EAX.

同时该函数使用该寄存器来存储变量 i.

At the same time the function uses this register for variable i.

所以在循环之后寄存器总是包含 44.

So after the loop the register always contains 44.

这个值接收调用者.

当然,该函数具有未定义的行为.它应该有一个显式的 return 语句,在循环之后的函数末尾带有一个表达式.

Of course the function has undefined behaviour. It shall have an explicit return statement with an expression at the end of the function after the loop.

这篇关于当函数最后缺少 return 语句时,为什么它会起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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