[patch] Java definite assignment

Per Bothner per@bothner.com
Tue Feb 6 13:42:00 GMT 2001

Mo DeJong <mdejong@cygnus.com> writes:

> Well, here is a much more simple case of the same thing,

No, it is very different, because there is no loop.

> are you saying this code should compile because the if
> statement can be reached and that the value of b does
> not matter?
> public class tmp {
>     void foo() {
>         int i;
>         boolean b = false;
>         if (b) {
>             i = 0;
>         }
>         i++;
>     }
> }

In this case the i++ is reachable, and i is not definitely assigned.

> GCJ currently errors out on this example:
> tmp.java:8: Variable `i' may not have been initialized.
>            i++;

That is correct.

> So, which one is incorrect?

The point is in:

        for (;;) {
           if (b) {
                i = 0;

the only way the loop can terminate is by executing the break
statement, and i *is* definitely assigned at that point.  Hence i is
definitely assigned after the loop.  However, i is *not* definitely
assigned after the 'if' statement, were there another statement there.

This is covered is gory detail in chapter 16 of the of the JLS
(original or revised online edition).  Once you "get the concept" it's
not hard to understand, but it takes a bit to get to that point.  Many
people misunderstand it.
	--Per Bothner
per@bothner.com   http://www.bothner.com/~per/

More information about the Java mailing list