Implicit to explicit type conversion


               In C++, type casting has two forms: Implicit type conversion - These conversions are performed by C++ in a type-safe manner ..... Explicit conversions require a cast operator.

Implicit Conversion 

         Whenever data types are mixed in an expression, C++ performs the conversion automatically this process is known as implicit or automatic conversion.

Example: m=5+2.5;

         For a binary operator, if the operands type differs, the compiler one of them to match with the other.Using the rule that the smaller type is converted to wider type.

         For example, if one operand is integer and another is float then integer is converted to float because float is wider than integer.

         In above example answer means m, will be in float.

Explicit Conversion

         C++ permits explicit type conversion of variables or expressions using the type cast operator.

Syntax: type_name(expression)

Example: average =sum/float(i);

         Alternatively we can typedef to create an identifier of the required type and use it in the functional notation.

Example:

typedef int * int_ptr;
p=int_ptr(q);

Example:

#include<iostream>
using namespace std;

int main()
{
        int intvar =5;
        float floatvar =3.5;

        cout<<"intvar ="<<intvar;
        cout<<"\n floatvar ="<<floatvar;
        cout<<"\n float(intvar) ="<<float(intvar);
        cout<<"\n float(floatvar) ="<<int(floatvar);

Output:

intvar = 5
floatvar =3.5
float(intvar) =5
int(floatvar) =3