Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

while(false) vs. if(false)

 
Adam Tkaczyk
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I don't know why
statement
if(false) {...} compiles fine, but
while(false){...} makes compilation error.
Is this a bug?
 
Jari Timonen
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Code is never reached aka. executed. (Compiler error, Unreachable statement)
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Adam,

Java uses a simple flow analysis algorithm to find most common cases of unreachable code, and all such unreachable code blocks will be flagged as compile-time errors. That's why your "while (false) { ... }" statement produces an error.

However, Java makes a special exception for "if (false) { ... }", because programmers often use this construct during development to temporarily disable part of the program. That's why the compiler accepts this statement.

If you're interested in the nitty-gritty details, refer to the Java Language Specification's description of unreachable statements.
 
Rahul Shilpakar
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If has ELSE statement in optional but while doesn't have.

while (false) doesn't make any sense because the code below it not gonna execute anyway. this is not the case with IF it has ELSE in option.

 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rahul,

Your argument is reasonable as well. But Sun's explicitly stated intention for allowing "if (false) { ... }" was to allow "conditional compilation" of code, i.e. having code that can be enabled or disabled based on a debug flag value that's a compile-time constant. For example:

Note that because DEBUG is a compile-time constant, you'll get a compiler error if you replace any of the "if (DEBUG) { ... }" statements with "while (DEBUG) { ... }".
[ December 11, 2007: Message edited by: Kelvin Lim ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic