Does static_cast generate the same (primitive) type of any code?

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

But here is an example. Considering,

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

does

 functionThatTakesAFloat(static_cast<float>(f)); 

creates additional code compared to

 functionThatTakesAFloat(f); 

or is this static_cast completely eliminated by the compiler?

Edit: I am using VC ++ (2010)

+6
source share
3 answers

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

+6
source

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 is...

 f(static_cast<float>(my_float)); 

... should be equivalent ...

 float temp = my_float; f(temp); 

Whether this is done literally literally and generates a timeline in non-optimized builds, it depends on the compiler. If you do not trust your optimizer to remove this (if it has ever been inserted), you should try another compiler ...; -).

+10
source

Ideally, the compiler should never create additional code for any casting operation (except dynamic_cast<> ), especially for such primitive types.

0
source

Source: https://habr.com/ru/post/886852/


All Articles