开发者

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

functionThatTakesAFl开发者_运维百科oat(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜