any news on const/invariant?

Steven Schveighoffer schveiguy at yahoo.com
Tue Nov 27 06:41:03 PST 2007


"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.  It 
seems a bit fuzzy because in D we think of arrays as pointers, but they are 
really structures, passed by value.

Let's assume your wish was granted and headconst was available.  Now the 
code becomes:

void GammaAdjust(headconst byte *bitmap, int length, double adjustment)
{
   // want to realloc bitmap? oops! can't do it, I'll just use a different 
variable
   byte *tmp = malloc(length + 1);
   memcpy(tmp, bitmap, length);
   tmp[length] = 5;
   // work on tmp...
}

our coder has now realized that he cannot change the bitmap pointer, so he 
just allocates a new one.  This is the same as the previous example, except 
now we just use a different variable.  You have not solved the problem, and 
that is: any coder who does not understand the semantics of variable passing 
is not going to be saved by anything the compiler can enforce.  I believe 
the second example is more obvious than the first, but both are still 
obvious to me, and even the example where byte[] is used is obvious to me :) 
I think what we need is a better explanation to new coders on how arrays 
work and are passed to functions.

I agree with Walter's position regarding head const.

-Steve 





More information about the Digitalmars-d mailing list