so what exactly is const supposed to mean?
Bruno Medeiros
brunodomedeirosATgmail at SPAM.com
Mon Jul 3 06:29:01 PDT 2006
Sean Kelly wrote:
>
> > and doesn't D already have a const keyword?
>
> D has const as a storage attribute, which is a bit different from the
> above. D's const may only apply to concrete data types, and implies
> that the data will never be modified for the duration of the program.
> This allows the compiler to place such data in ROM and to perform some
> optimizations that would otherwise not be possible. But this is quite
> limited in that it may only be applied to data that can be evaluated at
> compile-time.
>
There is a slight difference from D's const and a const that places the
data in ROM as you cannot get the address of a D const var (it's not an
lvalue).
Resummarizing:
D's const has two meanings. The usual meaning is from the form:
const int var = <some constant initializer>;
and it means that the variable is a compile-time constant and no storage
is allocated for it, instead the value is substituted whenever the var
is used (like #define, but safer).
The second meaning is from the form:
const int var; // no initializer
and means that the var must be initialized once in a constructor, and
then it becomes non-recursively immutable (meaning you can't change the
value of the var, but you can change referenced values). The var has
storage and as such is an lvalue.
This is basically the same as final in other languages (Java, C#), and I
wonder why it isn't in D as well(?). Walter said he didn't want a const
keyword overloaded with many different meanings.
--
Bruno Medeiros - CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D
More information about the Digitalmars-d-learn
mailing list