Loading...
C++

Type Conversion

An expression may involve variables and constants either of same data type of different data types. However, when an expression consist of mixed data type then they are converted to the same type while evaluation, to avoid compatibility issues. This is accomplishes by type conversion, which is defined as the process of converting one predefined data type into another. Type conversions are of two types, namely
1.Implicit Conversions
2. Explicit Conversions

  1. Implicit Conversions:
    Implicit conversion, also known as automatic type conversion refers to the type conversion that is automatically performed by the compiler. Whenever compiler confronts a mixed type expression, first of all char and short int values are converted to int. This conversion is known as integral promotion. After applying this conversion, all the other operands are converted to the type of the largest operand and the result is of the type of the largest operand. The  implicit conversion of data type starting from the smallest to the largest data type. For example 10+5.54, the compiler converts the int into float as float is larger than int and then then perform the addition. 
  2. Explicit Type Conversion:[Typecasting]
    Typecasting refers to the type conversion that is performed explicitly using type cast operation. In C++, typecasting can be performed by using two different forms which are given here.
    data_type(expression)   //expression in parentheses
    (data_type)expression   //data type  in parentheses
    where,
    data_type=data type (also known as cast operator) to which the expression is to be converted. To understand typecasting, consider this example.
    float(num)+5.5; // num is of int type
    In this example, float() acts as a conversion function which converts int to  float. However, this form of conversion cannot be used in some situations. For example, consider this statement.
    ptr=int*(x);
    In such cases, conversion can be done using the second from of typecasting as shown here
    ptr=(int*)x;

Leave a Reply

Your email address will not be published. Required fields are marked *