Explicit type casting operator in C++


A type cast provides a method for explicit conversion of the type of an object in a specific situation. It can be used as a unary expression −

( type-name ) cast-expression

The compiler treats cast-expression as type type-name after a typecast has been made. Casts are used to convert objects of any scalar kind to or from the other scalar type. Explicit type casts are constrained by the same rules that determine the effects of implicit conversions. Additional restraints on casts could result from the actual sizes or representation of specific types 

example

#include
using namespace std;
int main() {
   float x = 3.1;
   int i;
   i = (int)x;

   cout << x << ", " << i << endl;
   return 0;
}

Output

This will give the output −

3.1, 3


Updated on: 11-Feb-2020

458 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements