> You can't declare a variable here. In JLS-speak:
>
[quoted text clipped - 21 lines]
>
> is of course OK.
Thanks very much for the explanation. I don't think this is well known, at
least not by textbook authors (one of whom used this code in a test question
bank, indicating the correct answer is: ans = 120).
A local variable declaration with initialization not a statement.
Interesting. Same code works fine in C++, but that's not pertinent.
As your explanation suggests, adding {} will allow the code to compile.
I learned something today. I appreciate you taking the time...
Mike Schilling - 14 Jul 2005 20:15 GMT
> Thanks very much for the explanation. I don't think this is well known, at
> least not by textbook authors (one of whom used this code in a test
> question bank, indicating the correct answer is: ans = 120).
> A local variable declaration with initialization not a statement.
Certainly it's a statement in the normal use of that term, but it's not a
Statement in the JLS's Backus-Naur grammar.
> Interesting. Same code works fine in C++, but that's not pertinent.
That's a really bad idea, I would think.
i = 0;
if (i > 0)
int ans = 12;
if (ans > 0) // is ans declared here? If so, what is its value?
But C++, unlike Java, has no rules to force variables to be initialized
before they're used.