• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Loops and if statements

 
Fitz Herbert
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. Try compiling this:

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 test could 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic