簡體   English   中英

為什么我會收到警告“死碼”?

[英]Why am I get a warning “Dead code”?

    if (myCondition1 && myCondition2 && myCondition3)
    {
    ...
    }

我編寫了這段代碼並成功運行。 但我對(...)的一部分發出了警告。 警告是“死代碼”。 這對我來說很有趣。 你有什么想法嗎? 感謝你

“死代碼”是永遠不會被執行的代碼。 很可能你的某個條件在某處被硬編碼為false ,使條件內的if始終為false。

死代碼意味着永遠不會執行。 例如

void someMethod() {
    System.out.println("Some text");
    return;
    System.out.println("Another Some text"); // this is dead code, because this will never be printed
}

在您的狀況檢查時也是如此

String obj = "";
if(obj == null && obj.equals("")) { // here you get warning for Dead code because obj is not null and first condition is false so obj.equals("") will never evaluate

}

永遠不會到達塊中的代碼。 原因很可能是其中一個條件總是錯誤的。

如果myCondition1,myCondition2和myCondition3中的一個或多個始終為false(如私有const bool myCondition1 = false;)那么if中的代碼將永遠不會被執行。

這可能由於多種原因而發生。 整個if塊都死了 ,由以下內容引起:

boolean condition1 = true;
boolean condition 2 = !condition1;

if(condition1 && condition2) {
    //This code is all dead
    Foo f = fooFactory();
    f.barr(new Bazz());
}

或者你無條件地使用returnbreakcontinue類的東西離開if塊,如下所示:

for(Foo f : foos) {
    if(true) {
        f.barr(new Bazz());
        break;
        //Everything after here is dead
        System.out.println("O noes. I won't get printed :(");
    }
}

暫無
暫無

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

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