2

有人可以给我一个为什么我在使用三元运算符时不能返回表达式的原因吗?

while( root != nullptr )
{
    if( current->data > v ) {
        ( current->left == nullptr ) ? return false : current = current->left;
    } else if( current->data < v ) {
        current->right == nullptr ? return false : current = current->right;
    } else if( current->data == v ) {
        return true;
    }
}
return false;

为什么我尝试返回 false 时会出错?我知道我可以这样做:

return ( ( 0 == 1 ) ? 0 : 1 );

但是当只是试图从一个表达式返回时,编译器有什么问题呢?

4

2 回答 2

8

问题是该return语句没有定义的值(它不是表达式),而三元运算符的右两个元素中的每一个都应该有一个值。您的代码中还有一个错误:循环应该测试current不是nullptr; root不会通过循环改变,所以循环永远不会正常退出。

只需将其重写为嵌套if语句:

current = root;
while( current != nullptr )
{
    if( current->data > v ) {
        if( current->left == nullptr ) return false;
        current = current->left;
    } else if( current->data < v ) {
        if( current->right == nullptr) return false;
        current = current->right;
    } else if( current->data == v ) {
        return true;
    }
}
return false;

事实上,尽管如此,对于这个特定的逻辑,您根本不需要内部return语句:

current = root;
while( current != nullptr )
{
    if( current->data > v ) {
        current = current->left;
    } else if( current->data < v ) {
        current = current->right;
    } else if( current->data == v ) {
        return true;
    }
}
return false;

但是,如果您喜欢三元运算符并且必须使用它,您可以:

current = root;
while( current != nullptr )
{
    if( current->data == v ) {
        return true;
    }
    current = (current->data > v) ? current->left : current->right;
}
return false;
于 2012-09-10T18:21:28.030 回答
2

三元运算符从多个子表达式创建一个新表达式。return语句不是表达式。

于 2012-09-10T18:24:06.610 回答