Thank you!

Tejas notrealemail at gmail.com
Tue Sep 7 13:27:10 UTC 2021


On Tuesday, 7 September 2021 at 05:36:17 UTC, jfondren wrote:
> On Tuesday, 7 September 2021 at 05:09:39 UTC, jfondren wrote:
>> On Tuesday, 7 September 2021 at 05:01:30 UTC, Tejas wrote:
>>> This reminds me of single length string literals being 
>>> treated as a character.
>>>
>>> ```d
>>> void main(){
>>>      char[5] a = "y";//shouldn't compile, but it does
>>>      char[5] b = 'y';
>>>      writeln(a);
>>>      writeln(b);
>>> }
>>>
>>>
>>> Output:
>>> y
>>> yyyyy
>>> ```
>>>
>>> Was it a good thing that the compiler rewrote the string into 
>>> a char in this case? Wouldn't it be better if an 
>>> error/warning was provided instead?
>>
>> This example works with a initialized to "yy" as well, or 
>> "yyxx". The chars not provided are initialized to 0 (rather 
>> than 255 if the variable weren't initialized at all). This 
>> seems like a nice way to reuse a large fixed buffer that 
>> initially has small relevant content, like `char[255] line = 
>> "hello";`
>>
>> It doesn't initialize the entire array to 'y', so it's not 
>> treating "y" as the same as 'y'.
>
> Seems strange to only permit this with a string literal though.
>
> ```d
> unittest {
>     char[3] a;
>     char[2] b = '!';
>
>     // this is OK
>     a = "!!";
>     assert(a == [33, 33, 0]);
>
>     // Error: mismatched array lengths, 3 and 2
>     assert(!__traits(compiles, a = ['!', '!']));
>     assert(!__traits(compiles, { a[] = b[]; }));
> }
> ```


You can work around this problem with designated initializers

```d
void main(){
     char[3] a = [0:'!', /*no need for "1:"*/'!', 2:char.init/*you 
  MUST assign explicitly to the last member of the array otherwise 
you get mismatched length error for some reason. Also note that 
this is only necessary when you use "0:" */];
     a[0 .. b.length] = b[];//this is the only way since a and b 
are of different types
}
```


More information about the Digitalmars-d mailing list