Strange implicit conversion integers on concatenation
Paul Backus
snarwin at gmail.com
Mon Nov 5 16:10:52 UTC 2018
On Monday, 5 November 2018 at 15:36:31 UTC, uranuz wrote:
> Hello to everyone! By mistake I typed some code like the
> following without using [std.conv: to] and get strange result.
> I believe that following code shouldn't even compile, but it
> does and gives non-printable symbol appended at the end of
> string.
> The same problem is encountered even without [enum]. Just using
> plain integer value gives the same. Is it a bug or someone
> realy could rely on this behaviour?
>
> import std.stdio;
>
> enum TestEnum: ulong {
> Item1 = 2,
> Item3 = 5
> }
>
> void main()
> {
> string res = `Number value: ` ~ TestEnum.Item1;
> writeln(res);
> }
>
> Output:
> Number value:
It seems like the integer 2 is being implicitly converted to a
char--specifically, the character U+0002 Start of Text.
Normally, a ulong wouldn't be implicitly convertible to a char,
but compile-time constants appear to get special treatment as
long as their values are in the correct range. If you try it with
a number too big to fit in a char, you get an error:
void main()
{
import std.stdio;
writeln("test " ~ 256);
}
Error: incompatible types for ("test ") ~ (256): string and int
More information about the Digitalmars-d
mailing list