casts/casts1.cc - Examples of static casting in C++. | Lecture 3 - slide 6 : 27 Program 1 |
// In this example we initialize with the non-narrowing initializer {}. // This makes it possible to illustrates the effect of static casting. #include <iostream> #include <string> int main(){ // Static casting int to double: int k{3}; double e{k}; // error (warning): narrowing conversion of k from int to double double f{static_cast<double>(k)}; // f initialized to 3.0 std::cout << f <<std::endl; // 3 // Static casting double to int: double d{123.456}; int i{d}; // error (warning): narrowing conversion of d from double to int int j{static_cast<int>(d)}; // j initialized to 123 std::cout << j <<std::endl; // 123 }