Constants, Aliases

Alexander Panek a.panek at brainsware.org
Thu Dec 14 03:57:58 PST 2006


Xinok wrote:
> In C++, you can define a constant by using a preprocessor:
> #define INT 30
> 
> In D, the standard is to use 'const':
> const int INT = 30;
> 
> The problem with the const keyword is it doesn't guarantee the expression will
> be constant.
> const int* PTR = new int; // This technically isn't a constant, the compiler
> just doesn't allow you to modify it's value.

Technically, you can change a constant value in C++, too, if you want. 
Just get the address and write a little inline assembler to mov x, y 
something else there. I can't imagine what'd hold me off from that.

If you really are so afraid constant values could be changed during 
runtime, then wright an immutable class, that does for you what you 
think you need more than D's const.
> 
> Another solution is to use enumerators, but they don't aloow any type other
> than int:
> enum { val = 30 } // OK
> enum { str = "Hello" } // Error
> 

enum : uint { } // Yay, we've got uint as enum!
enum : char { } // Yay, char too! (this works.)

The only thing that does not work is an array. Apart from that, you can 
use any (basic?) type.

> 
> So I was thinking, why not give this job to aliases? Aliases must be constant,
> you can use any type with them, and they're easy to write.
> alias 30 VAL;
> alias "Hello" STR;
> alias 31.5 DEC;
> 

This is neither type-safe nor anyhow what alias is meant to be.

> Expressions can simply be put within parenthesis:
> alias (15 * 99) EXP;

Same goes here.


Sorry, if I sound a bit harsh, but I really dislike preprocessors and is 
really great /without/ preprocessors. I don't see any need for this. You 
got version() statements, static if's and what not. It's way cleaner and 
  simpler to read, why insert something in the language just half a 
month before the language goes 1.0, that is *actually* deprecated and 
(IIRC) has been discussed in other forms already a few times?

Really. No need for that. D is not C++.

Kind Regards,
Alex



More information about the Digitalmars-d mailing list