unnecessary casts

Jonathan M Davis jmdavisProg at gmx.com
Wed Jan 30 16:01:39 PST 2013


On Wednesday, January 30, 2013 23:49:00 Namespace wrote:
> Is the compiler (dmd) fit enough to detect and avoid unnecessary
> casts?
> 
> E.g.
> [code]
> void foo(T)(T num) {
> int f = cast(int) num;
> // ...
> }
> 
> foo(42); // cast is unnecessary
> foo(4.2); // cast is necessary
> [/code]
> 
> Or should I wrote everytime
> 
> [code]
> void foo(T)(T num) {
> static if (is(T == int) || isImplicitlyConvertible!(T, int)) {
> int f = num;
> } else {
> int f = cast(int) num;
> }
> // ...
> }
> [/code]
> 
> Until now I count on the compiler, that it detect this cases and
> avoid casts. But I'm not 100% sure, so I want to ask.

You'd have to look at the generated code to know for sure what it did, but it 
would be poor optimization to not strip the cast when casting from a value to 
its own type. And really, I'd argue that it's premature optimization to really 
worry about it in the first place. I'd argue that it's a bug if unnecessary 
casts are not optimized out, but unless you're searching for compiler bugs, 
there shouldn't be any reason to worry about it.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list