Okay, what happened to my literal strings?

Steven Schveighoffer schveiguy at yahoo.com
Mon Sep 10 06:03:20 PDT 2007


"Bill Baxter" wrote
> Burton Radons wrote:
>>
>> A good example is "char* strchr (const char*, char)" from C. That implies 
>> that the return value is not a pointer to an index of the first argument, 
>> but it is, it's just not declared that way because the argument itself 
>> may not be const. So the signature misses the subtlety of the true 
>> contract. If the user uses this signature as self-documentation then they 
>> could easily make an error. If it were instead "const char* strchr (const 
>> char*, char)" then the contract goes beyond what is strictly required 
>> because it's so blunt, and interpreted as self-documentation requires the 
>> user to make a copy before any modifications of the return value (and 
>> makes it impossible to do certain operations). If we decide that we don't 
>> want to lie then we can declare it as "char* strchr (char*, char)", which 
>> implies that the function modifies the string (because of the absence of 
>> const), when it never does; interpreted as self-documentation you'd 
>> always call it with mutable data. There's no happy medium: in any case 
>> the self-documentation is wrong and harms the user.
>
> I think the actual "fix" in C++ would be just to define a version of 
> strchr overloaded on const.  So you have both:
>
>    const char* strchr(const char*, char);
> and
>    char* strchr(char*, char);
>
> If you pass it a char* that can be modified, it'll give you back one that 
> can be modified. Otherwise it won't.
>
> --bb

This is not a "fix" as Burton is describing the constness as a contract for 
the compiler to interpret.  It solves the problem of being able to pass 
const and non-const data to a function which does the same thing, and having 
it return the correct argument type.  However, the compiler doesn't know 
that both functions are the same.  How would the compiler know that the 
second function is not going to change any data in the string?  Legally, the 
second function _can_ change data.

The challenge is: Define the prototype for strchr in a way that it can be 
interpreted as not changing the data supplied by the argument, but will 
return the same type (const or non-const) that you pass in.  Oh, and it 
can't cast away constness in the function, because that would be undefined 
;)

-Steve 





More information about the Digitalmars-d mailing list