C++ Type Conversion

In this tutorial you will learn about the C++ Type Conversion and its application with practical example.

C++ Type Conversion

C++ is a strong-typed language, which mean have associated data type with a variable before it is being used in program. Type conversion is basically way to convert an expression of a given type into another type. When a variable is converted into a different type, the compiler basically treats the variable as of the new data type. In C++, there are two types of type conversion –

Type of Conversion

  • implicit conversion
  • explicit conversion

Implicit Conversion

In implicit or automatic conversion compiler will automatically change one type of data into another. For instance, if you assign an integer value to a floating-point variable, the compiler will insert code to convert the int to a float.

Example:-

Here value of 'a' has been promoted from short to int and we have not had to specify any type-casting operator. implicit conversions affect fundamental data types. Typecasting should always be used in right order (low to higher datatype).Typecasting in wrong places may result in loss of precision, which the compiler can signal with a warning. for example like for instance truncating a float when typecasting to an int.This can be avoided with an explicit conversion. Below is the right order for numerical conversion.

short int -> int -> unsigned int ->long int -> unsigned long int -> float -> double -> long double

Explicit Conversion

It allows you to make this type conversion explicit, or to force it when it wouldn’t normally happen.To perform type casting, put the desired type including modifiers (like double) inside parentheses to the left of the variable or constant you want to cast. In C++, there are two ways we can perform generic type casting –

Recommended:-  C++ for Loop

Syntax 1:-

Example:-

Syntax 2:-

Example:-

In this tutorial we have learn about the C++ Type Conversion and its application with practical example. I hope you will like this tutorial.