On const ambiguity

Bruno Medeiros brunodomedeiros+spam at com.gmail
Tue Nov 14 05:35:40 PST 2006


Tomas Lindquist Olsen wrote:
> 
> a static in a class is well defined. so is a const. for me 'static 
> const' reads as having the 'static' redundant. a 'const' in D is by 
> definition static. It cannot change, as only a compile-time constant 
> will qualify, and thus will be the same to all classes of whatever reads 
> it.
> a function 'const' is very much the same. I fail to come up with a 
> scenario where choosing the storage model for a constant makes any sense!
> Can you post an example of why we need 'static const' ?

Much like "auto", D's "const" is ambiguous, it represents two different 
concepts:
   compile time constant.
   read-only variable(assign only once), same as "final" in Java and C#.

You get the first with something like:
   const int foo = 2; // compile time constant
You get the second with:
   const int foo;
   this() {
     foo = 2;
   }
that is, the final-like-const variable (foo here) must be initialized in 
the constructor of the class/struct or module where it is a member of.


So, the compile-time-const does not make sense with "static", but the 
final-like-const does:

---
module test;

static const int foo;

static this() {
   foo = 42;
}

void test() {
   int a = foo; // Ok
   foo = 2;  // Error "can only initialize const foo inside constructor"
             // AKA foo is final
}

-- 
Bruno Medeiros - MSc in CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D



More information about the Digitalmars-d mailing list