Re: Incorrect "variable might not have been initialized"
"Robert Klemme" <bob.news@gmx.net> wrote in message
news:4b96blFvqaucU1@individual.net...
Chris Uppal wrote:
Another example where the compiler (wrongly IMO) treats an assignment as
a
constant expression:
int number ;
String ref ;
if (((number = 6) > 0) && (ref = System.getProperty("user.home")) !=
null)
System.out.println(ref) ;
So at least it's consistent ;-) Maybe the JLS (I'm looking at version 3)
should be changed. Whatever it is /intended/ to mean, it doesn't seem to
consider this case specifically, and I think it should.
Do you think that because of formal reasons (completeness of the spec) or
for practical reasons? IMHO the code presented in this thread is not
something one (at least I) would usually write.
The compiler is being pessimistic. That is, if it can't be sure that
assignment will have occured, it just assumes that assignment did not occur,
and reports an error. The alternative is for the compiler to be optimistic
(if it isn't sure, just assume the code is correct and compile it, possibly
leading to runtime errors later on). In terms of practicality, the more we
can minimize this pessimism (or optimism, if you have a compiler designed
with optimism), the more "useful" the compiler will be. However, we can
never make the compiler 100% correct (in the sense of never pessimistic nor
optimistic, but always exactly correct), because it's been proven that this
is equivalent to solving the Halting Problme, which has been proven to be
impossible to solve.
With that in mind, if the compiler is "correctly" detecting a definite
assignment, even though the JLS says it shouldn't, we should probably change
the JLS to reflect that we can expect this extra bit of usefulness, rather
than changing the compiler to become "less useful" and rigidly following the
spec.
- Oliver