Copyright © tutorialspoint.com

C++ Casting Operators

previous next


A cast is a special operator that forces one data type to be converted into another. As an operator, a cast is unary and has the same precedence as any other unary operator.

The most general cast supported by most of the C++ compilers is as follows:

(type) expression 

Where type is the desired data type. There are other casting operators supported by C++, they are listed below:

All of the above mentioned casting operators will be used while working with classes and objects. For now try following example to understand a simple cast operators available in C++. Copy and paste following C++ program in test.cpp file and compile and run this program.

#include <iostream>
using namespace std;
 
main()
{
   double a = 21.09399;
   float b = 10.20;
   int c ;
 
   c = (int) a;
   cout << "Line 1 - Value of (int)a is :" << c << endl ;
   
   c = (int) b;
   cout << "Line 2 - Value of (int)b is  :" << c << endl ;
   
   return 0;
}

When the above code is compiled and executed, it produces following result:

Line 1 - Value of (int)a is :21
Line 2 - Value of (int)b is  :10

previous next

Copyright © tutorialspoint.com