Thank you!

Tejas notrealemail at gmail.com
Tue Sep 7 06:45:02 UTC 2021


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


More information about the Digitalmars-d mailing list