any news on const/invariant?

Derek Parnell derek at psych.ward
Tue Nov 27 13:25:23 PST 2007


On Tue, 27 Nov 2007 09:41:03 -0500, Steven Schveighoffer wrote:

> "Derek Parnell" wrote
>> On Mon, 26 Nov 2007 21:24:13 -0800, Walter Bright wrote:
>>
>>> I'm not sure why one would need protection against changing the bitmap
>>> pointer. GammaAdjust should just take a byte[], not a ref byte[].
>>
>> byte[] bitmap;
>> bitmap = LoadBitMapFromFile("worldroadmap.bmp");
>> GammaAdjust(bitmap, 0.20);
>> Render(device, bitmap);
>>
>> If the 'GammaAdjust' routine changed the pointer then 'Render' routine
>> would not display the adjusted bitmap.
>>
>> So I would like to tell the compiler that 'GammaAdjust' is not allowed to
>> change the pointer and thus if (at compile time) it does so the compiler
>> should tell me of the error.
> 
> I think you are missing something here.  Let's view this as it really is, a 
> pointer with a length:
> 
> void GammaAdjust(byte *bitmap, int length, double adjustment)
> {
>    // want to realloc bitmap?
>    byte *tmp = bitmap;
>    bitmap = malloc(length + 1); // don't really know the right way to do 
> this :)
>    memcpy(bitmap, tmp, length);
>    bitmap[length] = 5;
>    // work on bitmap...
> }
> 
> Now does any reasonable C coder expect this to work correctly?  no.


Arrrgh! 

I'm talking about accidently or inadvertant attempts to change a pointer's
value. I'm talking about allowing the compiler to help the coder.


void GammaAdjust(byte* const(bitmap), int length, double adjustment)
{
   // want to realloc bitmap?
   byte *tmp = bitmap; 
   bitmap = malloc(length + 1); // BANG! Compiler shouldn't allow this.

   memcpy(bitmap, tmp, length);
   bitmap[length] = 5; // But this is okay.
   // work on bitmap...
}

-- 
Derek Parnell
Melbourne, Australia
skype: derek.j.parnell



More information about the Digitalmars-d mailing list