非空函数工作正常,即使没有执行返回 [英] non-void function works fine even without executing return

查看:168
本文介绍了非空函数工作正常,即使没有执行返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个计算机科学大学生。昨天,我有一个关于使用C ++的二叉搜索树的课程。

I'm a computer science college student. Yesterday, I have a class about Binary Search Tree using C++. We are taught by lab assistants in that class.

它们将树中的节点定义为如下的结构:

They define the node in the tree as a struct like this :

struct Data{
    char name[15];
    int age;
    Data *left,*right;
};

,他们给我们一个代码,在BST中搜索如下:

and they give us a code to search within the BST like this:

// temp is current node, name is the value of the node to be searched for.
Data* search(Data *temp,char name[]) {
    if(strcmp(temp->name,name)>0)
        search(temp->left,name);
    else if(strcmp(temp->name,name)<0)
        search(temp->right,name);
    else
        return temp;
}

我注意到代码错误。 如果函数进入第一个或第二个if块,它将不会执行任何返回语句。

I notice that code is wrong. If the function gets into the first or the second if block, it will not execute any return statement.

但是当实验室助理运行代码,它工作正常。

But when the lab assistant run the code, it works just fine.

我想也许这种行为是编译器特定的。
但是当我试图在gcc上的代码,该函数也工作正常。 (我们大学使用microsoft visual c ++编译器)

I thought maybe this behaviour is compiler specific. But when I tried that code on gcc, the function also work fine. (our university uses microsoft visual c++ compiler)

任何人都可以解释发生了什么?为什么这个代码工作?

Can anyone explain what is happening? why is this code working?

PS:忽略其他错误,例如当节点为空,未找到值等。

PS: ignore other errors such as when the node is empty, the value is not found, etc.

推荐答案

这只是未定义的行为。

It's just undefined behavior.

出现工作,因为有一个寄存器保存返回值。在递归树的最深路径中, temp 被移入该寄存器,并且从未被清除或更改,因此寄存器将包含正确的节点,直到第一次调用返回。

It appears to work because there's one register that holds the return value. In the deepest paths of the recursion tree, the temp is moved into that register, and never cleared or changed afterwards, so that register will contain the correct node until the first call returns.

当第一个调用返回时,调用上下文检查该寄存器的返回值,这恰好是正确的。但你不应该依赖这个。 它不安全,假设它总是工作。

When the first call returns, the calling context checks that register for the return value, which happens to be correct. But you shouldn't rely on this. It's not safe to assume it will always work.

这篇关于非空函数工作正常,即使没有执行返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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