Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

casting

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)

like image 245
Robert Hegner Avatar asked Apr 28 '11 06:04

Robert Hegner


1 Answers

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

like image 117
Tony Delroy Avatar answered Oct 10 '22 09:10

Tony Delroy