• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

funny "for loop"

 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does not compile:


Compiles fine:

I think that compiler wants to prevent us - the first statement is useless - we do not do anything with int - just declaring, but when we add curly braces the situation is different. We have THE SCOPE of an int in which that variable can be used, so compier doesn't give any error.

Am I right?
Correct me if I am wrong.
 
Henry Wong
author
Marshal
Pie
Posts: 21423
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Short answer.... it is simply defined that way. The JLS defines the body of a ForStatement as having a Statement. A LocalVariableDeclaration is *not* one of the options of Statement, hence, illegal for the first case. In the second case, a BlockStatement is an option for Statement, and a BlockStatement is defined to contain LocalVariableDeclarations, hence, legal.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic