我从博客中发现了一些 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/