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

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Oct 5 03:29:50 PDT 2015


On Monday, October 05, 2015 09:07:34 Marc Schütz via Digitalmars-d-learn wrote:
> 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

That depends on whether VRP can figure out that the result will fit.
Otherwise, you'd be stuck with int. As it stands, all of these would just
end up with int, I believe, though if they're assigned to a char and the int
is a constant, then VRP may kick in and make a cast unnecessary.

But discussions on whether types like char, wchar, dchar or bool should be
treated like integral types can get interesting. Walter clearly favors
treating them as integral types where as a number of us would much prefer
that they weren't. But both sides of the argument can show where the other
side's desired behavior would be problematic.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list