What is Type Conversion?

The type conversion is an operation that takes a data object of one type and creates the equivalent data objects of multiple types. The signature of a type conversion operation is given as

                   conversion_op :type1→type2

There are two types of type conversions which are as follows −

  • Implicit type conversion (Coercions) − The programming languages that enable mixed-mode expressions should describe conventions for implicit operand type conversions.

Coercion is defined as an automatic conversion between types. For example in Pascal, if the operands for the addition operation are of integer type and other real types, one of then the integer data object is implicitly changed to type real earlier the addition is implemented.

  • Explicit type conversion − Some languages support few efficiencies for doing explicit conversions, both widening and narrowing. In some cases, warning messages are created when an explicit narrowing conversion results in a meaningful change to the value of the object being modified.

For example, Pascal supports a built-in function round that changes a real-number data object to an integer data object with a value similar to the rounded value of the real. In C-based languages, explicit type conversions are known as casts. The desired type is located in parentheses only before the expression to be modified, as shown in (int) X for float X converts the value of X to type integer. One of the reasons for the parenthesis in C conversions is that C has several two-word type names, such as long int.

Advantages of Type Conversion

There are the following advantages of type conversion which are as follows −

  • If during type checking, a mismatch appears between the actual type of an argument and the expected type for that operation, then type conversion easily converts the data object implicitly and prevents the error.

  • In some languages such as C, type conversion is a built-in function, which implicitly casts an expression to convert it to the correct type.

  • Type conversion is automatically invoked in certain cases of mismatch. For example, in Pascal, if the arguments for an arithmetic operation including ‘+’ are of mixed real and integer type, the integer data object is implicitly converted to type real earlier the addition is implemented.

  • There is no data is hidden. Because each short integer can be defined as a long integer, no data is hidden by necessarily invoking a short int→long int.

  • With dynamic type checking, conversions or coercions are built at the point that the type mismatch is recognized during execution. For such languages narrowing conversions can be enabled. For static type checking, more code is added to the compiled program.

  • Type conversion is a subtitle need when there is a large number of data types in a programming language.