Dismantling the Christmas Tree

Mike Streatfield dnewsgroup.c at talyst.me.uk
Thu Sep 13 06:19:14 PDT 2007


Georg Wrede wrote:
> 
> CONST
> 
> Today we need to simply start with a clean slate with const.
> 
> We need to go back to basics, to the actual needs that we want const to 
> cater for.
> 
 > We should also step back and give another try at enumerating (and
 > sorting) the primary issues we are trying to achieve with const. Here
 > again, every programmer and his granny seem to /really and fully/ know
 > the what and the why. (*4) Before we can go further, we really need to
 > be on the same board.
 >

Lately, when programming in C++ I've found myself getting bogged down in 
whether I'm using const in the right places for the right things. When I 
recently switched to try out D for a new project, const really didn't 
seem to work in the same way at all so I dropped it, it was quite 
refreshing not to have to worry about where and when to use const in 
code and actually made me more productive.

However, I have found I've been missing being able to use const in a 
couple of cases, both of which I use essentially as a safety net. I'm 
sure these are fairly common use cases and I've not used D 2.0, so for 
all I know these are covered already, but I thought I'd contribute them 
anyway, in case they help any.


1) When declaring parameters of functions. There are a lot of cases 
where I use const to ensure that I don't accidentally change values 
passed in from another source. C++'s *const syntax was especially useful 
for this (and const references, for that matter). For example:

// Ok, I've not thought too hard about naming, but say I have
// a game state enumeration and I want to update my game's
// AI behaviour based on it. I wish to use gameState in the
// function but ensure I don't accidentally change it. Even though
// the funciton has a local copy of this int, I would rather
// the compiler caught any deviation from my intention.

void updateAIBehaviour(const int gameState)
{
	gameState = ROBOTS_ATTACK; // Compiler error here.
}



2) Essentially the same case, but when generating variables internally. 
I actually prefer Java's final syntax here, but C++ const is almost good 
enough. The idea is setting a variable once and not changing it after, 
for the same reasons as the previous case.

// Generate a height value for a terrain heightmap given the x and
// z values on the horizontal plane.
int generateHeight(int x, int z)
{
	// I wish to calculate cx once and maintain it's value
	// henceforth
	const int cx = x - OFFSET_X;

	cx = 37; // Compiler error.
}



More information about the Digitalmars-d mailing list