Cpp - Explicit Type Conversion

Introduction

You can convert an expression explicitly using the cast operator (type).

(type) expression 

The code above converts the value of an expression to the given type.

Explicit type conversion is known as casting.

The cast operator (type) is a unary operator and thus has a higher precedence than the arithmetic operators.

int a = 1, b = 4; 
double x; 
x = (double)a/b; 

In the code above the value of a is explicitly converted to a double.

Following the implicit type conversion, b is converted to double and a floating-point division is performed.

The exact result, 0.25, is assigned to the variable x.

Without casting, an integer division with a result of 0 will be returned.

Demo

#include <iostream> 
#include <iomanip> 
using namespace std; 
int main() /* ww  w  .j a  v a  2 s.  c o m*/
{ 
   char v_char = 'A'; 
   cout << "v_char:       " << setw(10) << v_char 
                                 << setw(10) << (int)v_char 
                                 << endl; 
   short v_short = -2; 
   cout << "v_short:      " << dec << setw(10) << v_short 
                                 << hex << setw(10) << v_short 
                                 << endl; 
   unsigned short  v_ushort = v_short; 
   cout << "v_ushort:     " << dec << setw(10) << v_ushort 
                                 << hex << setw(10) << v_ushort 
                                 << endl; 
   unsigned long  v_ulong = v_short; 
   cout << "v_ulong:      " << hex << setw(20) << v_ulong 
         << endl; 
   float  v_float = -1.99F; 
   cout << "v_float:      " << setw(10) << v_float << endl; 
   cout << "(int)v_float: " << setw(10) 
                                 << dec << (int)v_float << endl; 
   return 0; 
}

Result