Do we really need const?

Bruce Adams tortoise_74 at yeah.who.co.uk
Mon Sep 17 17:07:37 PDT 2007


Bill Baxter Wrote:

> Regan Heath wrote:
> > renoX wrote:
> >> Bruce Adams a écrit :
> >>> An example of one that catches me out quite often is:
> >>> strcpy(src,dest) vs. strcpy(dest,src);
> >>
> >> If it helps you'not the only one to have this kind of issue: some 
> >> compilers even try to detect when people makes mistakes for 'memset'?
> >> Both case show why function calls with passing the parameter by 
> >> position instead of by keywords *sucks*.
> >>
> >> Let's try it: do you think you would make the same mistake if you 
> >> would call your function this way:
> >> char[50] var_dest, my_src;
> >> strcpy(dest: var_dest, src: my_src)
> > 
> > My eyes... aaarghh!
> 
> Is it the particular syntax or the concept you object to?  I think 
> named/keyword parameters can be quite useful.  Have you ever used a 
> language that has them?
> 
> I think the problem with putting them into D is only that it becomes yet 
> another way to do things.  We already have all the flavors of 
> overloading inherited from C++.
> 
> --bb

Actually I quite like the concept of keywords provided they're optional.
I prefer the Fortran-90 syntax:

copy(source=foo, dest=bar);

since its sort of an assignment.
Actually its just as ugly, but you can get used to almost anything
eventually.

That protects me from one kind of bug where I get source and dest confused. It does not protect me from getting foo and bar confused. If the source is required to be const and foo is not the const variable I am saved. 

i.e.
   myfunc( string alpha = var1, string beta = var2 )
   {
       stuff...
       copy(var2,var1);
   }

vs.
   myfunc( const string alpha , string beta )
   {
       stuff...
       copy(source=alpha,dest = beta);
   }


   string var1 = "source"
   string var2; //uninitialised oh no!
   myfunc(alpha=var1,beta=var2);

The const protects me from swapping args when the keywords hide some implementaiton detail. However, agreed positional arguments are a bad thing in general but sometimes necessary.
In the above it would be useful to say - must be initialised which in C++
is:  const var1 = "source";
Though, a ordinary clever compiler detect that var2 is not initialised without const.

So cost benefit analysis so far. Keywords yes, maybe even before const but not a replacement.

Regards,

Bruce.




More information about the Digitalmars-d mailing list