1

我有一个二叉搜索树的插入功能,但我不知道为什么会出现该错误。即使我返回 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
4

1 回答 1

0

即使一个函数实际上确实在所有可能的路径上返回了一些东西,编译器也不一定能确定——在所有情况下都能够这样做将有效地证明停止问题是可以解决的。这就是为什么此诊断是警告而不是错误的原因。

这是一个很容易看到总是 return 的函数示例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内部的 a 。while如果您希望是这种情况,您可能希望添加一个始终失败的断言。此外,您可能会考虑将这个循环更改while (cursor != NULL)for (;;)哪些“文档”,该循环只会因为内部的returnorbreak语句而结束(并且可能assert(cursor != NULL)在顶部有一个)。

只是为了记录,在return FALSE;你的函数结束之前放一个会使警告静音。

于 2012-05-01T14:30:20.447 回答