• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why this for loop doesnt compile  RSS feed

 
mo radesh
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
im curious of why this is legal

if(false){}

but this is not

for(;false;){}

both will in theory never go in

more interestingly

this will compile

for(;false == false;){}

To me it seems like this is a parsing issue that could have been solved by the people who originally wrote the parser but they made a decision that there must be a relational operator in the condition declaration.
Kind of odd to me.
 
mo radesh
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
with an exception to the rule that ofcouse this is allowed

for(;true;){}

and the whole "must be a relational operator in the condition declaration" idea goes away..
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Normally the Java compiler stops with an error if you have unreachable code (code which is in a place where the compiler knows it will never be executed). Therefore, you would expect that this is not allowed:

But this is a special case that is allowed, see Conditional compilation in the Java Language Specification.

The idea to allow this is to make it easy for developers to temporarily "comment out" a block of code, for debugging / testing purposes.

Also see 14.21 Unreachable statements.
 
mo radesh
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you for the clearification
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mo radesh wrote:
more interestingly

this will compile

for(;false == false;){}

Well why wouldn't it ?
It's equivalent to
for(;true;){}
which, as you said, is allowed.
 
mo radesh
Greenhorn
Posts: 8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
good point

I dont know what was going on in my head at the moment

in my defence my daughter was running around when I was testing this
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!