Concatenation of ubyte[] to char[] works, but assignation doesn't

Marc Schütz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Oct 5 02:07:34 PDT 2015


On Sunday, 4 October 2015 at 21:57:44 UTC, Jonathan M Davis wrote:
> On Sunday, October 04, 2015 16:13:47 skilion via 
> Digitalmars-d-learn wrote:
>> Is this allowed by the language or it is a compiler bug ?
>>
>> void main() {
>>     char[] a = "abc".dup;
>>     ubyte[] b = [1, 2, 3];
>>     a = b;   // cannot implicitly convert expression (b) of 
>> type
>> ubyte[] to char[]
>>     a ~= b;  // works
>> }
>
> When appending, b to a, the elements in b are being copied onto 
> the end of a, and presumably it works in this case, because a 
> ubyte is implicitly convertible to char. But all it's doing is 
> converting the individual elements. It's not converting the 
> array.
>
> On other hand, assigning b to a would require converting the 
> array, and array types don't implicitly convert to one another, 
> even if their elements do.
>
> Honestly, I think that the fact that the character types 
> implicitly convert to and from the integral types of the 
> corresponding size is problematic at best and error-prone at 
> worst, since it almost never makes sense to do something like 
> append a ubyte to string. However, if it didn't work, then 
> you'd have to do a lot more casting when you do math on 
> characters, which would cause its own set of potential bugs. 
> So, we're kind of screwed either way.

I don't think math would be a problem. There are some obvious 
rules that would likely just work with most existing code:

char + int = char
char - int = char
char - char = int
char + char = ERROR


More information about the Digitalmars-d-learn mailing list