Regis St-Gelais
Regis St-Gelais

Reputation: 3251

Dead code warning?

Why am I getting a dead code warning on the i++ in this function ?

InputFilter hexInputFilter()
    {
    return new InputFilter()
        {
            @Override
            public CharSequence filter(CharSequence source, int start,
                    int end, Spanned dest, int dstart, int dend)
                {
                for (int i = start; i < end; i++)
                    {
                    if ((source.charAt(i) >= '0')
                            && (source.charAt(i) <= '9'))
                        {
                        return null;
                        }
                    if ((Character.toUpperCase(source.charAt(i)) >= 'A')
                            && (Character.toUpperCase(source.charAt(i)) <= 'F'))
                        {
                        return null;
                        }
                    return "";
                    }
                return null;
                }
        };
    }

Upvotes: 26

Views: 77215

Answers (4)

Faiz Ahsan
Faiz Ahsan

Reputation: 41

In your case, the below statement is causing the problem as it runs unconditionally and will always run when the for loop is executed. So it will never reach for i++ so its dead code.

return ""; 

Upvotes: 4

Cristian
Cristian

Reputation: 200080

There's no chance for the for to loop more than once because you are returning:

return "";

Thus, i++ won't be executed ever and that's why you get a dead code warning. Maybe you want to remove that return ""; and/or put it outside the for.

Upvotes: 60

Richard Miskin
Richard Miskin

Reputation: 1260

You'll only ever execute the loop once because of the return ""; statement.

Upvotes: 5

Gintautas Miliauskas
Gintautas Miliauskas

Reputation: 7892

That is because i++ is normally executed after the end of the for-block, and in your function the end of the for-block will never be reached because in the block you unconditionally return a value.

A for-loop

for (A; B; C) {
  D;
}

is internally translated into the following:

A;
while (B) {
  D;  
  C;
}

You can see that if D always returns from the function, C will never be reached. That's what the complaint is about.

Upvotes: 13

Related Questions