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

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

问题描述

我正在学习C ++。下面的代码让我感到困惑:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 40; i< 44; i ++)
{
if(i == a)
{
cout< 用i返回:<<我<< ENDL;
返回59;
}
}
}

int main()
{
cout<< in main:<< test_return(61)<< ENDL;
返回0;
}

我知道我在函数 test_return



但编译器说没有错误,并且在执行时有效。

所以我拿起一些特定的数字,如 40 44 59 61 查看哪一个函数 test_return

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

  in main:44 

好像这个函数 test_return 在for语句结束之前返回了int i



My问题是:



这是合法吗?



它是如何运作的?

更新:

在函数 test_return 的最后添加这些代码:

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

它出来了:

  in main:10000 

感谢来自莫斯科答案的@Vlad!它有帮助。

解决方案

如果有一台兼容英特尔的计算机,那么看起来该函数返回寄存器<$ c $中的结果c> EAX



同时该函数使用此寄存器作为变量i。



所以在循环后,寄存器总是包含44个。



这个值接收调用者。



当然这个函数具有未定义的行为。它应该在循环后面的函数末尾有一个显式的return语句。


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;
}

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.

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

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

My question is:

Is this legal?

How does it work?

Update:

I add these codes at the end of function test_return:

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

It comes out:

in main: 10000

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

解决方案

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

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

So after the loop the register always contains 44.

This value receives the caller.

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.

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

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