简体   繁体   中英

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)

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... ;-).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM