When the condition statement of a loop/if statement has a definate condition of false and so the loop/if statements body is never used, will this generate compliation errors, due to duff code?
Joined: Aug 03, 2002
Unlike C/C++ Java has no preprocessor to handle macros like #ifdef and #ifndef. So you cannot really do any sophisticated conditional compilation. But the Java compiler does let you write:
Provided that the "// statements" are well formed compilable Java code, these two if statements will be treated like conditional compiled code, and in the case of the false variation will not generate any bytecode. However if you try to use a while loop you will get unreachable code errors. [ May 07, 2003: Message edited by: Barry Gaunt ]
Trying to compile this will result in an "unreachable code" error. However, if you change it to this:
You won't get an error. The compiler isn't very thorough when it comes to checking conditions to see if they'll be executed. If it appears that the conditional testcould pass, the compiler lets it go. You can find a lot more information in the JLS, §14.20 Unreachable Statements. I hope that helps, Corey