const

Janice Caron caron800 at googlemail.com
Sun Mar 30 15:46:06 PDT 2008


On 30/03/2008, Scott S. McCoy <tag at cpan.org> wrote:
>
>
>  On Sat, 2008-03-29 at 00:05 -0700, Walter Bright wrote:
>  Janice Caron wrote:
> > I suggested that a declaration like
> >
> > const int x = 5;
> >
> > should be interpretted by the compiler as if the statement had been
> >
> > invariant int x = 5;
> >
>
> Yeah, but I can see the bug report now: "dammit, I typed it as const,
> why is it coming out as invariant?"
>
>  The last thing I want is for the compiler in a statically typed language to
> just decide to change my type for me.

Perhaps, but I don't think you've understood that it is /impossible/
to declare a const variable that isn't, in fact, invariant. Consider:

    const int x = 5;

x may be typed const(int), but it is, in fact, really, really,
invariant. Because not only can you not change it, but no one else can
either. It obeys the contract for invariance. The compiler knows that,
so should be able to take advantages of the optimization potential
thereof.

Furthermore, since invariant(int) implicitly casts to const(int), you
won't even /notice/ that this has happened, unless you explicitly do
writefln(typeof(x).stringof) or something.

This is provably a completely safe thing to do, and would be
transparent to the programmer apart from explicit type testing.

(Plus, in combination of some of my other ideas, it could help us get
rid of enum for manifest constants).



More information about the Digitalmars-d mailing list