Thank you!

bauss jj_1337 at live.dk
Tue Sep 7 09:27:59 UTC 2021


On Tuesday, 7 September 2021 at 06:45:02 UTC, Tejas wrote:
> On Tuesday, 7 September 2021 at 06:12:38 UTC, bauss 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?
>>
>> What you think is happening is not actually what's happening.
>>
>> It's not turning the string into a char. It's actually copying 
>> the contents of the string (char array) into the char array.
>>
>> It's evident by:
>>
>> ```d
>> char[5] c = "hello";
>> ```
>>
>> c will be "hello"
>>
>> And in the case of ex.
>>
>> ```d
>> char[5] c = "hello world!";
>> ```
>>
>> You actually get a runtime error but arguably it should be a 
>> compile-time error since the size of c and the size of the 
>> string is available at compile-time.
>>
>> I would agree with that it shouldn't be allowed at all 
>> however, but unfortunately this is allowed because string is 
>> really an alias for an array and not a type in itself.
>
> Nope, there is definitely some special-casing going on here.
>
> The following doesn't work:
> ```d
> import std.stdio;
>
> void main(){
>     immutable (char)[] s = "hello";
>     char[5] a = s;
>     writeln(a);
>     immutable (int)[] i = [10];
>     writeln(i);
>     int[] I = i;
> }
> ```
> Turn `I` into a static array, and you get runtime error for 
> some strange reason.
>
> This is an inconsistency.
>
> But considering the use case presented by @jfondren, I'm not 
> sure whether we should remove it for consistency's sake

Yeah, what I was saying is that there's some funky thing going on 
but that it wasn't turning the string into a char but rather 
somehow attempting to copy the string into the char array.


More information about the Digitalmars-d mailing list