CSS font stacks & developer FAQs with Web standards
Site navigation below

One of hundreds of answers available with our premium content service.

Part answer, see below for more

A: If you declare a variable in a for loop without braces the Sun compiler will fail with the message "not a statement", but the message is misleading. A more appropriate error message would be "o is already defined". In this case there is no contained scope for the variable o, so every pass through the loop would have the effect of declaring the variable again and again.

// Does not compile
for ( ; ; ) Out o = new Out();
    

Without braces its as if you had written a continuous list of variable declarations:

// Does not compile
Out o = new Out();
Out o = new Out();
...
    

In the example below the for loop statement is enclosed in curly braces, which gives the variable declaration more precise scope. In this case, each pass through the loop creates a "throw-away" variable which is local to the statement block.

for ( ; ; ) {

  // Compiles
  Out o = new Out();
}
    

This question is not particularly to do with the for loop and it makes no difference whether the loop runs once or an infinite number of times. The significant point is not to do with assignment, it is about the declaration of the variable and the scope the variable has. The annotated example below continues the case of the for loop, but the key is to compare the different syntax that follows the for conditions.

… full answer hidden

Click for full answers

Premium members click below for full answer
Why does this for loop instantiation fail to compile?

Un-social media

We love social media, but we do not expect you to create yet another public outpost on the Web.

Home · Web fonts · Font stacks · FAQs · Java · CSS · Javascript · HTML · Site manager