| | | | | |

Explicit Type Conversion: Casting

  • Best practice: use implicit type conversion only within one of these two families of native types:
  • Signed Family = {char, short, int, long, float, double, long double}
    Unsigned Family = {unsigned char, unsigned short, unsigned int, unsigned long}

  • Otherwise use explicit type conversion using cast operators
  • /* C casting operators */
    c = (char)y;   // cast a copy of the value of y as a char,
                   //  and assign to c
    x = (int)b;    // cast a copy of the value of b as an int,
                   //  and assign to x
    
    /* C++ static cast operator */
    c = static_cast<char>(y); 
    x = static_cast<int>(b); 
    
  • C++ installations may or may not recognize the C cast operator
  • Two other C++ cast operators:
    dynamic_cast<type_name>(expr) and reinterpret_cast<type_name>(expr)

| | Top of Page | 1. Basic C++: A Review - 15 of 21