Const sucks

Nathan Reed nathaniel.reed at gmail.com
Tue Sep 11 09:22:37 PDT 2007


Steven Schveighoffer wrote:
> Second, I'm trying to understand what the real purpose of this is.  Could 
> someone define the different types of memory and why we need different 
> declarations to put things in those different types?  For example, "doesn't 
> consume memory" doesn't make sense to me.  The bytes gotta go somewhere!

For numeric constants which are known at compile time, there's not 
necessarily a location in the executable's data-sections where they are 
stored; they may just be incorporated as immediate values into the 
machine instructions, and/or folded into other expressions at compile 
time.  (For string constants known at compile time they are still going 
to have to be stored in the executable image.)

However, if you ever take the address of such a constant it needs to 
actually be stored.  For a regular declaration of a const variable, the 
compiler can optimize away the stored version if it can determine that 
the address is never taken, but this often isn't possible (think of 
class member variables - the compiler can't guarantee that no client 
code will ever take the address).  On the other hand it would be illegal 
to take the address of a macro.

Thanks,
Nathan Reed



More information about the Digitalmars-d mailing list