any news on const/invariant?

Janice Caron caron800 at googlemail.com
Tue Nov 27 23:47:50 PST 2007


On Nov 28, 2007 4:29 AM, Walter Bright <newshound1 at digitalmars.com> wrote:
> Daniel Keep wrote:
> > The way I've understood it is that const is both a type constructor
> > *and* a storage class.
>
> That's right. It's a floor wax *and* a dessert topping!
>
> > When invoked with parenthesis, it's a type
> > constructor.  When invoked without, it's a storage class that happens to
> > apply the type constructor to whatever the type of the declaration is.
>
> That's right, too.

I think we do all understand this. The problem is that it took us
(...well, me at least...) a long time before I /did/ grok it. I had to
ask questions on this newsgroup, and have it all explained to me. This
overuse of the word "const" is, in fact, one of the things which
caused complaints that the D2.007 const is "a mess". Yes - the head
const/tail const distinction caused confusion, but in my book, the
double-use of the the words "const" and "invariant" in situations
where it's not always obvious which meaning is intended, was equally
part of the confusion, and therefore falls into the category of that
which you have to sort out.

Similar problems would arise if you made "static" or "private" into a
type constructor. I've no idea what such things might mean, but just
hypothetically, if one could define a type static(int) or
private(char)[], then /exactly the same/ confusion would arise. It is
coincidence that "const int x;" means the same thing as "const(int)
x;" It is not so helpful that the analogy does not extend to "const
int f()" meaning the same things as "const(int) f()".

I believe it is a mistake for the same keyword, "const", to double up
with both meanings. (And the same logic applies to "invariant"). Since
there is a clear need for the "const" type-constructor, we should keep
that. But there is less of a need for "const" as an attribute. Perhaps
we don't need it at all there. As has been suggested previously,
attributes of "const(this)" and "invariant(this)" can be used to
define const/invariant functions. "static" is largely taking over from
"const" in meaning "available at compile time", and soon we'll have
"macro" to fill out the remaining duties. If we ditch
const-as-an-attribute altogether, it would require only minor changes
to get code compiling again: e.g.

    const int[] table = [ 1, 2, 3, 4 ];

becomes

    const(int[]) table = [ 1, 2, 3, 4 ];

or perhaps even

    static int[] table = [ 1, 2, 3, 4 ];

All confusion is immediately eliminated, and everyone's happy. Even
the compiler! After all, it will still have a context-free grammar and
be fast to compile. It's a big win-win for everyone. The only downside
I can see is that it would break code, but since it would break it in
an easily fixable way, I don't see that as a big deal.



More information about the Digitalmars-d mailing list