What is Type casting in C++? Explain with example.

Type casting

Type casting is converting one type to another type.

When the compatible types are mixed in assignment, the value of right side is automatically converted to the type of the left side.

There are 2 type of casting in c++

  • Implicit type casting (Automatic type conversion)
  • Explicit type casting (Forceful casting)

Implicit Type Casting:-

This  type of casting is automatically done by the compiler, there is no need to give an instruction to the compiler for the casting. Here may be lost of data if small data type value is converted to big data type value.

For example:

Output:

Explicit Type Casting:-

Explicit type cast is done by the user explicitly, it can’t done by compiler automatically.

It can be done by 2 ways:

  • Converting by assignment
  • Converting using cast operator

Converting by assignment:-

Here define the required type in parenthesis in front of expression.

Syntax:

(type) expression

Where type is the data type to which the final result is converted.

Example:

output:

Converting using cast operator:-

A Cast operator is an unary operator which forces one data type to converted into another data type.

C++ supports 4 type of casting

  • Static Cast
  • Dynamic Cast
  • Const Cast
  • Reinterpret Cast

 

Example:

output:

Leave a Reply