我有一个二进制搜索树的插入功能,我无法找出我收到该错误的原因。即使我把返回FALSE;在函数结束之前它仍然发生。任何帮助表示赞赏。
boolean insert(NODE **root, Employee e){
NODE *cursor,*temp;
// boolean status;
temp = (NODE *)malloc(sizeof(NODE));
assert(temp != NULL);
temp->element = (Employee *)malloc(sizeof(Employee));
assert(temp -> element != NULL);
*(temp -> element) = e;
temp -> left = NULL;
temp -> right = NULL;
if (*root == NULL) {
*root = temp;
return TRUE;
}
// tree is non-empty
cursor = *root;
while (cursor != NULL) {
if(e.ID < cursor -> element -> ID){
if(cursor -> left == NULL){
cursor -> left = temp;
return TRUE;
}
else cursor = cursor -> left;
}
//e goes to the right
else {
if (e.ID > cursor -> element -> ID){
if(cursor -> right == NULL){
cursor -> right = temp;
return TRUE;
}
else
cursor = cursor -> right;
}
else { // e is already in the tree
free(temp -> element);
free(temp);
return FALSE;
}
}
} // while cursor != NULL
} // insert
答案 0 :(得分:0)
即使实际上的函数在所有可能的路径上都返回了某些内容,编译器也无法确定 - 在所有情况下能够这样做都能有效地证明停止问题是可解决的。这就是为什么这种诊断是警告,而不是错误。
这是一个容易看到总是返回0
的函数的示例,但是许多试图警告您未处理的返回路径的编译器将发出警告:
int foo( int x)
{
while (x >0) {
--x;
}
if (x == 0) return 0;
while (x < 0) {
++x;
}
if (x == 0) return 0;
}
然而,有时简单的分析可以确定所有控制路径都返回一个值。以下通常不会生成诊断:
int bar(int x)
{
if (x == 0)
return 0;
else
return 1;
}
在像你这样复杂的函数中,任何人(编译器或人类)都很难确定while()
循环永远不会终止,除非通过它内部的return
。如果您希望是这种情况,您可能希望添加一个始终在while
之后失败的断言。您也可以考虑将while (cursor != NULL)
更改为for (;;)
哪个'文档'这个循环只会因为内部有return
或break
语句而结束(并且可能有顶部有一个assert(cursor != NULL)
。
仅为记录,在功能结束前放置return FALSE;
会使警告静音。