C++ examples for Data Type:Cast
A static_cast is used for all conversions that are well-defined.
void func(int) {} int main() {/* w ww . j a v a 2 s . c o m*/ int i = 0x7fff; // Max pos value = 32767 long l; float f; // (1) Typical castless conversions: l = i; f = i; l = static_cast<long>(i); f = static_cast<float>(i); // (2) Narrowing conversions: i = l; // May lose digits i = f; // May lose info // eliminates warnings: i = static_cast<int>(l); i = static_cast<int>(f); char c = static_cast<char>(i); // (3) Forcing a conversion from void* : void* vp = &i; float* fp = (float*)vp; fp = static_cast<float*>(vp); // (4) Implicit type conversions, normally performed by the compiler: double d = 0.0; int x = d; // Automatic type conversion x = static_cast<int>(d); // More explicit func(d); // Automatic type conversion func(static_cast<int>(d)); // More explicit }