Robert Hegner
Robert Hegner

Reputation: 9366

Does a static_cast to the same (primitive) type produce any code?

I guess it's all said in the title...

But here's an example. Given

void functionThatTakesAFloat(float par);
float f = 3.5f;

does

functionThatTakesAFloat(static_cast<float>(f));

produce any additionial code compared to

functionThatTakesAFloat(f);

or is this static_cast completely eliminated by the compiler?

Edit: I'm using VC++ (2010)

Upvotes: 7

Views: 1649

Answers (3)

Tony Delroy
Tony Delroy

Reputation: 106076

5.2.9 /

-2- An expression e can be explicitly converted to a type T
    using a static_cast of the form static_cast<T>(e) if the
    declaration ``"T t(e);"'' is well-formed, for some invented
    temporary variable t (dcl.init). The effect of such an explicit
    conversion is the same as performing the declaration and
    initialization and then using the temporary variable as the
    result of the conversion. <cont...>

So given:

float my_float = ...;

...this...

f(static_cast<float>(my_float));

...must be equivalent to...

float temp = my_float;
f(temp);

Whether it's actually followed that literally, and generates a temp in non-optimised builds, would be up to the compiler. If you don't trust your optimiser to remove this (if it was ever inserted), then you should try another compiler... ;-).

Upvotes: 11

kqnr
kqnr

Reputation: 3596

The simple answer here is that by definition a cast from float to float is a no-op. There is no conceivable code that could worth emitting for this cast. It may be true that some compiler in this universe emits unquestionably redundant code in this case, but it is safe to assume that you will never encounter such a compiler.

Upvotes: 7

iammilind
iammilind

Reputation: 69988

Ideally compiler should never produce extra code for any casting operation (except dynamic_cast<>) especially for such primitive types.

Upvotes: 0

Related Questions