Does typecasting in C/C++ result in extra CPU cycles?
My understanding is that is should consume extra CPU cycles atleast in certain cases. Like typecasting from flo
There are different types of casts. C++ has different types of cast operators for the different types of casts. If we look at it in those terms, ...
static_cast will usually have a cost if you're converting from one type to another, especially if the target type is a different size than the source type. static_casts are sometimes used to cast a pointer from a derived type to a base type. This may also have a cost, especially if the derived class has multiple bases.
reinterpret_cast will usually not have a direct cost. Loosely speaking, this type of cast doesn't change the value, it just changes how it's interpreted. Note, however, that this may have an indirect cost. If you reinterpret a pointer to an array of bytes as a pointer to an int, then you may pay a cost each time you dereference that pointer unless the pointer is aligned as the platform expects.
const_cast should not cost anything if you're adding or removing constness, as it's mostly an annotation to the compiler. If you're using it to add or remove a volatile qualifier, then I suppose there may be a performance difference because it would enable or disable certain optimizations.
dynamic_cast, which is used to cast from a pointer to a base class to a pointer to a derived class, most certainly has a cost, as it must--at a minimum--check if the conversion is appropriate.
When you use a traditional C cast, you're essentially just asking the compiler to choose the more specific type of cast. So to figure out if your C cast has a cost, you need to figure out what type of cast it really is.