Const sucks

Janice Caron caron800 at googlemail.com
Tue Sep 11 09:25:34 PDT 2007


On 9/10/07, Walter Bright <newshound1 at digitalmars.com> wrote:
> o  const/invariant declarations will always allocate memory (so their
> addresses can be taken)

I'd hadn't really thought about this before. But now I have.

I want to be able to *express the idea* that the value I am declaring
shall never change. To my mind:

const int NUM_DAYS_IN_WEEK = 7;

successfully expresses that idea, and frankly, I whether or not
NUM_DAYS_IN_WEEK consumes memory should not be my call. That is an
implementation detail, and should be the compiler's problem, not mine.


> o  So, we still need a method to declare a constant that will not
> consume memory. We'll co-opt the future macro syntax for that:

Isn't that a bit like "register" or "inline"? Those keywords went the
way of the dodo because it was decreed that the compiler could do a
better job at figuring out what to inline or put in registers than the
programmer ever could.

Isn't this the same? Surely, the compiler can make the decision as to
whether or not the value gets stored in memory. Why should I have to?

If the program does not take the address, and if sizeof the variable
is sufficiently small, then don't store in memory, otherwise do. If
it's a library and you don't know what the calling code will do, let
the compiler take its best guess. If it guesses wrongly, then either a
few bytes of memory will have been consumed, or some jiggery pokery
will be required at the call site. But either way, don't make the
programmer choose.


> macro x = 3;
> macro s = "hello";

And bang goes type safety, right there!



More information about the Digitalmars-d mailing list