Const sucks

Nathan Reed nathaniel.reed at gmail.com
Tue Sep 11 11:15:43 PDT 2007


Janice Caron wrote:
> class C
> {
>     const int n = 42;
>     /* other stuff */
> }
> 
> Suppose you new a thousand of those things. What's the point of making
> a thousand ints, all the same. Why not just do:
> 
> class C
> {
>     static const int n = 42;
>     /* other stuff */
> }
> 
> and only consume four bytes.
> 
> I argue that per-class-instance const variables is so silly, that you
> might just as well let the compiler "disappear" them.

Fine for things that are known at compile time.  But it's also possible 
to have const variables whose values are not known till runtime.  For 
instance

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

or class instance variables:

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.

>> Although, as other
>> people have pointed out, this doesn't break type safety, just makes the
>> type not explicitly stated in the code.
> 
> And this is different to #define how exactly?

#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.

Thanks,
Nathan Reed



More information about the Digitalmars-d mailing list