c++ - C++ 中缺少 return 语句仍然可以工作

标签 c++ recursion return-value

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

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 下,您不会得到预期的结果。

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

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++ -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,我得到了这个:

$ 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,因此返回值很可能是从您调用的先前函数继承的)。

关于c++ - C++ 中缺少 return 语句仍然可以工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20963347/

相关文章:

c++ - 有没有通过打印字符来播放动画的c程序

c++ - 递归设置的 n 个元素的 k 元组组合

c++ - 按值(value)返回总是常量吗?

c++ - 为什么编译器不为 size_t 的负值生成警告?

c++ - 如何指示返回值需要删除?

c++ - GCC:调用静态对象的重写函数时出现异常

algorithm - 查找目录的大小

javascript - 使用 for 循环时,Javascript 中的洪水填充算法不会填充整个网格

sql - sqlite3命令行返回码不一致

javascript - Jquery:获取函数的返回值