简体   繁体   中英

Eclipse dead code warning - why am I getting it?

In the following loop, listeners is array list. Eclipse shows me warning i++ being dead code. I have now added full for loop at its entirety as it exists in the code. Listeners are passed to the function and I don't think there is a way for Eclipse to detect if the list is empty

for (int i = 0; i < listeners.size(); i++) {
  listener = getMessageListener(i);
  while (listener.isMessageAvailable()) {
    fireJob(listener);
  }
  log.info("Placed all the pending jobs because of termination signal");
}

However following simple loop does not generate same warning

for (int y = 0; y < 10; y++) {
    System.out.println(y);
}

To me, both look functionally same - standard for loop. Eclipse is very specific about highlighting i++ area and fix is to remove i++ .

Another observation is if I copy same loop to somewhere else, I don't get warning. So one possibility is eclipse could be thinking for whatever reasons loop won't be executed. But code in the block gets executed.

One thought: if you comment out the log.info(... line does the warning go away? Because if Eclipse is determining that something is causing the loop to terminate early it must be because of one of the following:

  1. the condition is always false. But that would make the body unreachable, so an Unreachable code error on the body. Not your case

    eg: in this example y++ is Dead code , but body is Unreachable code .

     for (int y = 0; false; y++) { System.out.println(y); } 
  2. some statement before the last statement is terminating your loop. But then some of the body would be unreachable or dead. Not your case

    eg: in this example y++ is Dead code , and the println in Unreachable code .

     for (int y = 0; y < 10; y++) { break; System.out.println(y); } 

    in this example y++ and println is Dead code .

     for (int y = 0; y < 10; y++) { if (true) { break; } System.out.println(y); } 
  3. last statement terminates the loop. That would make only the i++ Dead code . Not your case , but should be testable that it isn't your case by commenting out the last statement.

    eg: in this example only y++ is Dead code , but commenting out the break means there is no Dead code .

     for (int y = 0; y < 10; y++) { System.out.println(y); break; } 

So, I believe, if commenting out the last statement ( log line in your case) in the loop does not make the Dead code warning go away you must have found a bug in the warnings generator/compiler. If so, I hope you can reduce it for all our sakes so that a proper bug report can be submitted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM