C++ 中缺少 return 语句仍然可以工作 [英] Missing return statement in C++ can still work

查看:86
本文介绍了C++ 中缺少 return 语句仍然可以工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从博客中发现了一些 C++ 代码.我在 IDE 中测试了代码.即使没有递归调用中的返回语句(search(head->lchild, x) 和 search(head->rchild, x)),代码中的函数也能正常工作;谁能解释一下原因?

I came across some C++ code from a blog. I tested the code in my IDE. The function in the code can work properly even without the return statement in the recursion calls(the search(head->lchild, x) and the search(head->rchild, x)); Can anyone explain why?

Node* search(Node* head, int x){
      if(head == NULL) return NULL;
      else if(x == head->key) return head;
      else if(x <= head->key) search(head->lchild, x);
      else search(head->rchild, x);
}

推荐答案

您的代码具有未定义的行为,因此任何事情都可能发生,包括按照您的意愿行事.在 Clang 下,您不会得到预期的结果.

Your code has undefined behavior, so anything could happen, including doing what you intended. Under Clang, you don't get the result you expected.

我做了最少的修改,让您的代码编译并使用未定义行为的路径:

I made minimal modifications to get your code to compile and exercise the path with undefined behavior:

struct Node { int key; Node *lchild; Node *rchild; };
Node *search(Node *head, int x){
  if(head == nullptr) return nullptr;
  else if(x == head->key) return head;
  else if(x <= head->key) search(head->lchild, x);
  else search(head->rchild, x);
}
Node a { 0, nullptr, nullptr };
Node b { 1, &a, nullptr };
int main() { search(&b, 0); }

默认情况下,Clang 会警告您的代码,并导致您的代码在 -O0 处脱离函数末尾时崩溃:

Clang warns on your code by default, and causes your code to crash when it falls off the end of the function at -O0:

$ clang++ -std=c++11 wszdwp.cpp
wszdwp.cpp:7:1: warning: control may reach end of non-void function [-Wreturn-type]
}
^
1 warning generated.
$ ./a.out
zsh: illegal hardware instruction (core dumped)  ./a.out

使用 Clang 的 -fsanitize=undefined,我明白了:

With Clang's -fsanitize=undefined, I get this:

$ clang++ -std=c++11 -w -fsanitize=undefined wszdwp.cpp && ./a.out
wszdwp.cpp:2:7: runtime error: execution reached the end of a value-returning function without returning a value

代码可能对你有用,因为你的编译器有帮助地"在函数体的末尾放入了一个 ret 指令(没有填写返回值 reigster,所以返回值很可能是从你之前调用的函数继承而来的).

The code was probably working for you because your compiler "helpfully" put in a ret instruction at the end of the body of the function (without filling in the return value reigster, so the return value is likely to be inherited from the previous function you called).

这篇关于C++ 中缺少 return 语句仍然可以工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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