define should be the keyword for manifest constants

guslay guslay at gmail.com
Thu Dec 13 11:00:29 PST 2007


Janice Caron Wrote:

> On 12/13/07, Steven Schveighoffer <schveiguy at yahoo.com> wrote:
> > How would the compiler know when compiling a module with a constant whether
> > some other module is going to take the address of that constant?
> 
> You're thinking old-school. D is new-school. Imports don't just import
> symbols, they import abstract symbol trees. Saying "How would the
> compiler know when compiling a module with a constant whether some
> other module is going to take the address of that constant?" is like
> saying "How would the compiler know whether a template needs to be
> instantiated?". The point is, it doesn't need to - it just exports the
> AST.
> 
> In fact, you can mimic #define pi=3.14159 as
> 
>     template pi { const real pi = 3.14159 }
> 
> in one module, and it will take up zero storage space until someone
> (possibly in another module) instantiates it with something like
> 
>     real x = pi!;
> 
> Not that I'm suggesting that we use templates for compile-time
> constants! (That would be silly). But the fact that we can do it at
> all shows that it can be done.

1 - Code:

const real Pi = 3.14; // or the template version.
//...
real x = Pi;

2 - Compiler: 

Pi is const. Replace x dynamic initialisation with static init. Becomes real x = 3.14;

3 - All value assigment of Pi have been trivialy optimized away. Pi is not used anymore.

However, if Pi is addressable, someone in another module might have taken a reference to Pi. The compiler cannot know. Therefore, Pi cannot be optimized way. This is what take storage.

If Pi is "enum"-like, it's a symbol that is just a placeholder for a value. After its value has been propagated, is not required anymore. It does not take storage.





More information about the Digitalmars-d mailing list