2014-01-07 20 views
1

我遇到了博客中的一些C++代碼。我在我的IDE中測試了代碼。即使沒有遞歸調用中的返回語句(搜索(head-> lchild,x)和搜索(head-> rchild,x)),代碼中的函數也可以正常工作。誰能解釋爲什麼?在C++中缺少return語句仍然可以工作

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); 
} 
+3

這是未定義的行爲。出現工作是一個有效的選擇。 – chris

+0

打開警告? –

+0

@ShafikYaghmour,羞愧的問題標題是不是太有用的尋找作爲一個騙局。 – chris

回答

1

你的代碼有未定義的行爲,所以任何事情都可能發生,包括做你想要的。在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); } 

鏘提醒您的代碼在默認情況下,並導致你的代碼時,脫落的結尾崩潰在-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 

鏗鏘的-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,所以返回值可能會從先前的功能)。

1

定義一個沒有返回語句的非void函數有一個Undefined Bihavour和一個沒有表達式的返回語句。

的C++ 11說,在§ 6.6.3

6.6.3 The return statement 

2 A return statement with neither an expression nor a braced-init-list can be 
used only in functions that do not return a value, that is, a function with 
the return type void, a constructor (12.1), or a destructor (12.4). 

... 

Flowing off the end of a function is equivalent to a return with no value; 
this results in undefined behavior in a value-returning function. 

你必須打開你的編譯器警告:

g++ -Wall 

,你會得到錯誤:

warning: no return statement in function returning non-void [-Wreturn-type] 
} 
^