簡體   English   中英

這個“其他”如何工作?

[英]How does this 'else' work?

我收到一條警告,建議您使用大括號以避免歧義的“其他”。

如果放在方括號中,此代碼等效於什么? 還是這實際上讀作“否則”?

    void balance(Node * & x)
    {
        if (x == nullptr)
            return;
        if (height(x->left) - height(x->right) > 1)
            if(height(x->left->left) >= height(x->left->right))
                rotateLeft(x);
            else
                doubleRotateLeft(x);
        else                                                      // this one
        if (height(x->right) - height(x->left) > 1)
            if(height(x->right->right) >= height(x->right->left))
                rotateRight(x);
            else
                doubleRotateRight(x);

        x->height = max(height(x->left), height(x->right)) + 1;
    }

為了愛小貓,請使用方括號-特別是對於這種混亂情況。 是的, else if現在就是else if

它確實是“讀為'else if'”,但是,如果您要使用方括號,則(將來)或代碼的任何其他閱讀器甚至都不需要問什么代碼塊還可以做else屬於 ;-)

如果一段時間以后您要在return;之前添加更多代碼行,則使用方括號將產生更好的結果return; 塊。 在沒有括號的情況下,您可能會犯下“無辜的”錯誤,以完全更改代碼的邏輯。

else if在讀。 使用花括號和正確格式的等效代碼:

void balance(Node * & x)
{
    if (x == nullptr) {
        return;
    }
    if (height(x->left) - height(x->right) > 1) {
        if(height(x->left->left) >= height(x->left->right)) {
            rotateLeft(x);
        }
        else {
            doubleRotateLeft(x);
        }
    }
    else if (height(x->right) - height(x->left) > 1) {
        if(height(x->right->right) >= height(x->right->left)) {
            rotateRight(x);
        }
        else {
            doubleRotateRight(x);
        }
    }
    x->height = max(height(x->left), height(x->right)) + 1;
}
void balance(Node * & x)
{
    if (x == nullptr)
    {
        return;
    }
    if (height(x->left) - height(x->right) > 1)
    {
        if(height(x->left->left) >= height(x->left->right))
        {
            rotateLeft(x);
        }
        else
        {
            doubleRotateLeft(x);
        }
    }
    else if (height(x->right) - height(x->left) > 1) // this one
    {
        if(height(x->right->right) >= height(x->right->left))
        {
            rotateRight(x);
        }
        else
        {
            doubleRotateRight(x);
        }
    }

    x->height = max(height(x->left), height(x->right)) + 1;
}

這是編譯器認為您正在編寫的代碼。 因為“ else if”考慮了兩者之間無限制的空間,所以所有書籍都建議始終加括號。

我認為在您的情況下,自動括號和我從縮進中猜測的邏輯似乎提供了相同的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM