20-CS-122-001 Computer Science II Spring 2012
Type Casting Examples

Virtual functions, classes, inheritance, lists, queues, stacks, applications

#include < iostream.h >

void main() {
   long   a = 0;
   float  b = 355.0/113.0;
   short  c = 0;
   float  d = 0;
   char   e = 88;
   bool   f = false;
   
   cout << "\nSizes of various data types:";
   cout << "\n   Sizeof long:" << sizeof(long) <<
           "\n   Sizeof float:" << sizeof(float) <<
           "\n   Sizeof short int:" << sizeof(short int) <<
           "\n   Sizeof char:" << sizeof(char) <<
           "\n   Sizeof bool:" << sizeof(bool) << "\n\n";
   cout << "Initial values:\n";
   cout << "   a:" << a << " b:" << b << " c:" << c << " d:" << d
        << " e:" << e << " f:" << f << "\n\n";
   
   cout << "Cast of float b back to float d (just to make sure):\n";
   d = *(float *)&b;
   cout << "   d:" << d << " b:" << b << "\n\n";

   cout << "Cast of float b to long a:\n";
   a = *(long *)&b;
   cout << "   a:" << a << " b:" << b << "\n\n";
   
   cout << "Cast of float b to short c:\n";
   c = *(short *)&b;
   cout << "   c:" << c << " b:" << b << "\n\n";

   cout << "Cast of float b to char e:\n";
   e = *(char *)&b;
   cout << "   e:" << e << " b:" << b << "\n\n";

   cout << "Cast of float b to bool f:\n";
   f = *(bool *)&b;
   cout << "   f:" << f << " b:" << b << "\n\n";

   cout << "New values:\n";
   a = (1 << 30)+(1 << 22)+(1 << 14)+(1 << 6);
   b = 0; c = 0; d = 0; e = 66; f = false;
   cout << "   a:" << a << " b:" << b << " c:" << c << " d:" << d
        << " e:" << e << " f:" << f << "\n\n";
   
   cout << "Cast of long a to float b:\n";
   b = *(float *)&a;
   cout << "   b:" << b << " a:" << a << "\n\n";

   cout << "Cast of long a to short int c:\n";
   c = *(short *)&a;
   cout << "   c:" << c << " a:" << a << "\n\n";
   
   cout << "Cast of long a to char e:\n";
   e = *(char *)&a;
   cout << "   e:" << e << " a:" << a << "\n\n";
   
   cout << "Cast of long a to bool f:\n";
   f = *(bool *)&a;
   cout << "   f:" << f << " a:" << a << "\n\n";
}

// Sample Output:
//   Sizes of various data types:
//      Sizeof long:4
//      Sizeof float:4
//      Sizeof short int:2
//      Sizeof char:1
//      Sizeof bool:1
//
//   Initial values:
//      a:0 b:3.14159 c:0 d:0 e:X f:0
//
//   Cast of float b back to float d (just to make sure):
//      d:3.14159 b:3.14159
//
//   Cast of float b to long a:
//      a:1078530012 b:3.14159
//
//   Cast of float b to short c:
//      c:4060 b:3.14159
//
//   Cast of float b to char e:
//       e: b:3.14159
//
//   Cast of float b to bool f:
//       f:220 b:3.14159
//
//   New values:
//       a:1077952576 b:0 c:0 d:0 e:B f:0
//
//   Cast of long a to float b:
//       b:3.00392 a:1077952576
//
//   Cast of long a to short int c:
//       c:16448 a:1077952576
//
//   Cast of long a to char e:
//       e:@ a:1077952576
//
//   Cast of long a to bool f:
//       f:64 a:1077952576