null [re: spec#]

Walter Bright newshound2 at digitalmars.com
Sat Nov 6 22:02:07 PDT 2010


Jonathan M Davis wrote:
> Going C# or Java's route forces the programmer to 
> initialize variables even in cases where they know that it's not necessary 
> (which is annoying but may or may not be worth it),

Correct. It's not that doing flow analysis is hard, it's that it's impossible to 
do it correctly. So you wind up with wishy-washy messages that p "might not" be 
initialized, which is what the Java compiler does for this:

   class A
   {
        public void foo()
        {
            Object p;
            if (m)
                 p = new Object();
            if (m)
                 p.toString();  // <-- p might not have been initialized
        }
        boolean m;
   }

It even errors out if you write it as:

   class A
   {
        public void foo()
        {
            Object p;
            if (m)
                 p = new Object();
            if (p != null)  // <-- p might not have been initialized
                 p.toString();
        }
        boolean m;
   }

Note that the error message is on the null check!


More information about the Digitalmars-d mailing list