Const sucks

Janice Caron caron800 at googlemail.com
Tue Sep 11 11:36:06 PDT 2007


On 9/11/07, Nathan Reed <nathaniel.reed at gmail.com> wrote:

> void foo (int bar)
> {
>      const int baz = bar * 47;
>      ...
> }

That's not a class member variable. That's a local variable. It's a
different animal.

In the case of local variables, the compiler can decide whether or not
memory storage is required.


> class Foo
> {
>      const int bar;
>      this (int baz)
>      {
>          this.bar = baz;
>      }
> }
>
> The variable needs to be initialized but is then not supposed to change
> over its lifetime.

That can be done in different ways. Walter was originally going to
allow final for that purpose, but final is now dropped. I think that
the above example will not compile under Walter's new plans, because
const is unmodifiable even in a constructor. Of course, I could be
wrong. One way to rewrite that, though, would be

class Foo
{
     private int bar_;
     this (int baz)
     {
         bar_ = baz;
     }
     int bar() return bar_;
}


> #define does text substitution.  In C, you could write something like this:
>
> #define THREE 3
> float pi = THREE.14159;
>
> With D macros that would not be allowed.

True. But I want more than that. I want to be able to distinguish between

const int x = 42;
const uint x = 42;

etc.

And if I want type deduction, of course the following would work just fine:

const x = 42;



More information about the Digitalmars-d mailing list