kamal
kamal

Reputation: 1193

Why am I get a warning "Dead code"?

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

I wrote this code and run successfully. but I got warning about part of (...). The warning is "Dead code". It is just interesting to me. Do u have any idea? thank u

Upvotes: 2

Views: 242

Answers (5)

Nandkumar Tekale
Nandkumar Tekale

Reputation: 16158

Dead code means it is never going to execute. E.g.

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

Same in case of your condition checking e.g.

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

}

Upvotes: 3

Edd
Edd

Reputation: 3822

This could occur for a number of reasons. Either the whole of the if block is dead, caused by something like the following:

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

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

Or you unconditionally leave the if block using something like return, break or continue, as shown below:

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 :(");
    }
}

Upvotes: 0

victorvartan
victorvartan

Reputation: 1002

If one or more of myCondition1, myCondition2 and myCondition3 are always false (like private const bool myCondition1 = false;) then that code inside the if will never be executed.

Upvotes: 0

Petteri H
Petteri H

Reputation: 12202

Your code inside the block is never reached. The reason is most likely that one of the conditions is always false.

Upvotes: 0

Dylan
Dylan

Reputation: 13914

"Dead code" is code that will never be executed. Most likely one of your conditions is hard-coded to false somewhere, making the conditional inside the if always false.

Upvotes: 6

Related Questions