define should be the keyword for manifest constants

"Jérôme M. Berger" jeberger at free.fr
Thu Dec 13 11:44:53 PST 2007


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

guslay wrote:
> 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.
> 
	Yes it can. When the compiler compiles a given module, if this
module does not take the address of Pi, then the compiler does not
allocate any storage for it. If this module does take the address of
Pi, then the compiler allocates storage in a special section. Then,
when the linker creates the final executable, it can combine all
allocations for Pi into a single one. This is actually what already
happens for template functions (and now that I think about it, it's
probably what happens for Janice's Pi template too...

		Jerome
- --
+------------------------- Jerome M. BERGER ---------------------+
|    mailto:jeberger at free.fr      | ICQ:    238062172            |
|    http://jeberger.free.fr/     | Jabber: jeberger at jabber.fr   |
+---------------------------------+------------------------------+
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)

iD8DBQFHYYu0d0kWM4JG3k8RAkDsAKCejovzcBcqPEBae0HCySXDbLYx9QCgg5lM
rCU59t/Lr690482Um2+zwxg=
=NLyG
-----END PGP SIGNATURE-----



More information about the Digitalmars-d mailing list