Results 1 to 7 of 7
- 01-08-2010, 12:21 AM #1
Member
- Join Date
- Jan 2010
- Posts
- 15
- Rep Power
- 0
- 01-08-2010, 01:36 AM #2
Senior Member
- Join Date
- Aug 2008
- Posts
- 384
- Rep Power
- 5
It indeed doesn't. Interesting question :) I don't know :P
I die a little on the inside...
Every time I get shot.
- 01-08-2010, 02:10 AM #3
Because of scope. When you do { }, int j is existence inside the brackets. Without, you're trying to overload a variable name.
will work w/out brackets.Java Code:int j; for (int i=0; i<5; i++) j = i;
- 01-08-2010, 09:09 AM #4
Moderator
- Join Date
- Apr 2009
- Posts
- 10,484
- Rep Power
- 16
It's not scope.
It's to do with what you're allowed to have as the single line of an if statement without {}. A declaration is not allowed. It has to be a statement.
I'd quote the specifics, but I haven't got the JLS to hand.
- 01-08-2010, 02:15 PM #5
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,604
- Blog Entries
- 7
- Rep Power
- 17
I have: the syntax of a for-loop statement is basically: "for ( ... ) Statement" and a "Statement" is syntactically explained in paragraph "14.5 Statements"; a declaration is not a "Statement", it is part of a block which in turn is syntactically equivalent to a "Statement".
kind regards,
Jos
- 01-08-2010, 07:03 PM #6
Member
- Join Date
- Jan 2010
- Posts
- 15
- Rep Power
- 0
for loop without {} does not compile (does with {})
Yes, after some research:
Variable declarations are not allowed for short statements:
Blocks and Statements
Blocks and Statements
This is apparently to prevent dangling else statements. In a for statement, there wouldn't be a dangling else statement, but I can see why the same check is performed for short if statements and short for/while statements.
- 01-09-2010, 12:35 PM #7
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,604
- Blog Entries
- 7
- Rep Power
- 17
When you think of it if a declaration would've been a statement if strongly complicates the scoping rules, e.g.
The body of the for-loop is never executed if n < 0. Should it be determinable at runtime? That is not how lexical scoping works, so Gosling wisely decided that a declaration cannot be a statement.Java Code:for (int i= 0; i < n; i++) int x; x= 42; // does x exist?
kind regards,
JosLast edited by JosAH; 01-10-2010 at 12:09 PM.
Similar Threads
-
while-loop stopping on first loop
By davester in forum New To JavaReplies: 6Last Post: 06-26-2009, 08:46 PM -
Code will not compile
By ShotGunRockets in forum New To JavaReplies: 17Last Post: 05-10-2009, 03:31 AM -
compile problem
By chrisbremen in forum New To JavaReplies: 8Last Post: 11-13-2008, 06:20 PM -
doesn't compile?!
By jon80 in forum New To JavaReplies: 8Last Post: 06-14-2008, 05:42 PM -
Not able to compile
By bugger in forum New To JavaReplies: 2Last Post: 01-09-2008, 10:13 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks