Why implicit conversion of string literal to char[] does not works?
Regan Heath
regan at netmail.co.nz
Tue Jul 2 06:48:27 PDT 2013
On Tue, 02 Jul 2013 14:33:09 +0100, Michal Minich
<michal.minich at gmail.com> wrote:
> On Tuesday, 2 July 2013 at 13:07:40 UTC, Regan Heath wrote:
>> It is done for performance reasons. On UNIX the compiler will put the
>> literal "abc" into read only memory. It could/should do the same on
>> windows but doesn't yet (I believe).
>>
>> So, the compiler is treating them as such, by giving them the type
>> immutable(char)[] (AKA string).
>>
>> And, the spec should, if it doesn't, define string literals to be
>> immutable.
>>
>
> Ok I understand. What I did as a first thing when I get error on "char[]
> x = "a" was "char x = cast(char[])"a", Which was obviously incorrect -
> as the "a" was/should be placed in rom. So if this expression is allays
> wrong - casting string literal to mutable, then compiler should emit an
> error on this (If one implementation (dmd/win) makes this valid, it
> still doesn't mean compiler should honor implementation over
> specification - amusing it is specified that strings go into rom...)"
As Dicebot has replied, cast() is the mechanism the programmer uses to
force the compiler to do what s/he wants regardless of what it thinks.
The compiler assumes that if cast() is used that the programmer knows what
they're doing. Only use cast() if you have no other option.
In this simple case, the compiler could detect the error, or as you say
below take the cast(char[]) as a hint to place the "a" in RAM instead.
But, 99.9% of cases are more complex than this simple one, so the
cost/benefit of detecting the error make it very low priority, perhaps
never to be implemented. Likewise for the place in RAM idea. Both/either
would be nice, but neither is necessary now provide a lot of benefit.
> Also, given you explanation, I see it as good to type "auto x = "a" as
> string, but give explicit notation char[] x = "a" - I don't see reason
> to not allow string literal to be typed as both char[] and string at the
> same time, and convert to char[] - and also place in ram, if explicitly
> asked.
To explicitly place "a" in RAM you would write
char[] x = "a".dup;
Or:
char[] x = new char[1];
x[0] = 'a';
> The only reason that comes now to mi mind is when working with old code
> base - before auto and immutable(char)[] .. the code had to use char[] x
> = "a", but these must be all eliminated by now....
Old code using char[] x = "a" was technically invalid (it just happened to
run ok on windows, or linux if no mutation was done) and will now error as
such.
For old code raising this error the correct solution ..
- if mutable is required is to add ".dup".
- if mutable is not required is to replace "char[]" with "string" or
"auto".
R
--
Using Opera's revolutionary email client: http://www.opera.com/mail/
More information about the Digitalmars-d-announce
mailing list