Casts, especially array casts
bearophile
bearophileHUGS at lycos.com
Wed Feb 24 14:09:00 PST 2010
Jonathan M Davis:
> Languages like Java and C# manage safe casting with only one type of cast.<
In C# you have implicit and explicit casts (used with the same syntax, I think).
> Can't the compiler figure out which cast is supposed to be used in a given
> situation and deal with it internally?
In this example the conversion can be a trunc of the float, or it can be a reinterpret of the bits contained in the float as an int, the compiler can't tell them apart (currently D performs the trunc/round/ceil, according to the FP flags):
float x = 10.5;
int y = cast(int)x;
The same happens in the conversions of arrays, as I have explained in the post.
> I'd prefer a performance
> penalty in the rare case when I have to cast rather than having to worry
> about whether I or anyone else on a project that I'm working on is using the
> various cast types correctly.
It's not just a matter of performance, it's also a matter of keeping the semantics more tidy, because currently different operations are conflated in the same syntax.
I think D programmers can appreciate to have a way to tell apart the two kinds of casts I have explained, also because 90% of the times you can use the normal (run-time) cast, that can be called just cast() or dcast(). In most cases that's what you want, you can use it as the default one, and use a scast or static_cast when you want to reinterpret the bits of a value, struct or array, pointer (or class reference).
At the moment cast() performs a static cast on run time arrays, a dynamic cast on array literals, a dynamic cast on values, a dynamic cast on class references, and I think a static cast between signed and unsigned integers. And to convert an integer into a string you need to!(). In my opinion this situation is a bit too much messy.
Bye,
bearophile
More information about the Digitalmars-d
mailing list