[chuck-users] initialization of static variables

Robert Poor rdpoor at gmail.com
Tue Dec 8 20:11:53 EST 2009


Gang:

I now understand a bit more about initialization of static variables  
-- more accurately, about execution of top-level code -- and while  
it's not earth-shattering, I thought I'd pass it along.  It may avoid  
some astonishment.

The rules are simple, but are different than I thought:

-- top level forms INSIDE a class definition are executed every time  
an instance of that class is created.

-- top level forms OUTSIDE of a class definition are executed once  
when the file loads.

To see the implication on initializing a static variable, consider the  
following:

===== file: t1.ck
public class Statix {
     // UNO is set with to new value at every call to 'new Statix'
     static Object @ UNO; (new Object) @=> UNO;

     // DUE is set once after the first call to 'new Statix'
     static Object @ DUE; if (DUE == null) (new Object) @=> DUE;

     // TRE is set once when the file is loaded (see below)
     static Object @ TRE;

     <<< "at a: UNO=", Statix.UNO, "DUE=", Statix.DUE, "TRE=",  
Statix.TRE >>>;
}
<<< "at b: UNO=", Statix.UNO, "DUE=", Statix.DUE, "TRE=", Statix.TRE  
 >>>;
(new Statix) @=> Statix.TRE;
<<< "at c: UNO=", Statix.UNO, "DUE=", Statix.DUE, "TRE=", Statix.TRE  
 >>>;

===== file: t2.ck
<<< "at d: UNO=", Statix.UNO, "DUE=", Statix.DUE, "TRE=", Statix.TRE  
 >>>;
new Statix @=> Statix @ _t1;
<<< "at e: UNO=", Statix.UNO, "DUE=", Statix.DUE, "TRE=", Statix.TRE  
 >>>;
new Statix @=> Statix @ _t2;
<<< "at f: UNO=", Statix.UNO, "DUE=", Statix.DUE, "TRE=", Statix.TRE  
 >>>;

===== the output:
% chuck t1.ck t2.ck
at b: UNO= 0x0 DUE= 0x0 TRE= 0x0
at a: UNO= 0x5e5aa0 DUE= 0x5e5af0 TRE= 0x0
at c: UNO= 0x5e5aa0 DUE= 0x5e5af0 TRE= 0x5e6670
at d: UNO= 0x5e5aa0 DUE= 0x5e5af0 TRE= 0x5e6670
at a: UNO= 0x5e6ba0 DUE= 0x5e5af0 TRE= 0x5e6670
at e: UNO= 0x5e6ba0 DUE= 0x5e5af0 TRE= 0x5e6670
at a: UNO= 0x5e6c00 DUE= 0x5e5af0 TRE= 0x5e6670
at f: UNO= 0x5e6c00 DUE= 0x5e5af0 TRE= 0x5e6670



More information about the chuck-users mailing list