[Issue 8660] New: Unclear semantics of array literals of char type, vs string literals

monarch_dodra monarchdodra at gmail.com
Fri Sep 14 08:18:44 PDT 2012


On Friday, 14 September 2012 at 15:00:29 UTC, Don Clugston wrote:
> On 14/09/12 14:50, monarch_dodra wrote:
>> On Friday, 14 September 2012 at 11:28:04 UTC, Don wrote:
>>> --- Comment #0 from Don <clugdbug at yahoo.com.au> 2012-09-14 
>>> 04:28:17
>>> PDT ---
>>> Array literals of char type, have completely different 
>>> semantics from
>>> string
>>> literals. In module scope:
>>>
>>> char[] x = ['a'];  // OK -- array literals can have an 
>>> implicit .dup
>>> char[] y = "b";    // illegal
>>>
>>> A second difference is that string literals have a trailing 
>>> \0. It's
>>> important
>>> for compatibility with C, but is barely mentioned in the 
>>> spec. The
>>> spec does
>>> not state if the trailing \0 is still present after 
>>> operations like
>>> concatenation.
>>
>> I think this is the normal behavior actually. When you write 
>> "char[] x =
>> ['a'];", you are not actually "newing" (or "dup"-ing) any 
>> data. You are
>> just letting x point to a stack allocated array of chars.
>
> I don't think you've looked at the compiler source code...
> The dup is in e2ir.c:4820.
>
>> So the
>> assignment is legal (but kind of unsafe actually, if you ever 
>> leak x).
>
> Yes it's legal. In my view it is a design mistake in the 
> language.
> The issue now is how to minimize the damage from it.

Thank you for taking the time to educate me. I still have a bit 
of trouble with static vs dynamic array initializations: Things 
don't work quite as in C++, which is confusing me. I'll need to 
study a bit harder how array initializations work. Good news is 
I'm learning.

I think ALL my comments were wrong.

In that case, you are right, since:
char[] x = "a".dup;
Is legal.

>> Good point. For anybody reading though, the actual code 
>> example should be
>> enum char[] x = foo(true);   // ok
>> enum char[] y = foo(false);  // rejected!
>
> No it should not.
> The code example was correct. These are static variables.

I hadn't thought of static variables: I placed your code in a 
main, and both produced a compilation error. The enums reproduced 
the issue for me however.

>> I think this would work with my "m" suggestion
>
> Not necessary. This is only a question about what happens with 
> the compiler internals.

Yes.


More information about the Digitalmars-d-bugs mailing list