Type Casting

Type casting or type conversion is a technique which is used to convert the value of one predefined data type into another data type, typically will change size or interpretation property. The size may widen or narrow.

Rules when performing arithmetic operations on data:

  1. An arithmetic operation performed between an integer data type with integer data type is always integer. Eg: 1+2=3, 5*10=15, 5/2=2.
  2. An arithmetic operation performed between a float data type with float data type is always float. Eg: 1.1+2.9=4.0, 5.0/2.0=2.5.
  3. An arithmetic operation performed between an integer data type and a float data type is float. Eg: 1+3.5=4.5, 2*2.2=4.4, 5/2.0=2.5.

Type casting is of 2 types:

1. Implicit conversion or Automatic conversion: In this type of conversion we do not need to specify a data type, it automatically assigns a value of one data type into another. Assigning a smaller data type into a larger data type is known as Implicit conversion. Loss of value is not possible in Implicit conversion.

int a = 10;
float b = a; //type casting

Example 1: WAP to explain the use of Implicit/Automatic conversion.

void main()
{
    int a=10, b=4;
    float c;
    clrscr();
    c=a/b; //implicit conversion: convert result into float
    cout<<"After Implicit Conversion = "<<c;
    getch();
}
After Implicit Conversion = 2

2. Explicit conversion or Forcefully conversion: In this type of conversion, we need to place the name of the desired data type in the parentheses immediately before the value to be converted. Assigning a larger data type value into a smaller data type is known as explicit conversion. In explicit conversion, loss of value may be possible.

float x = 10.5;
int y = (int)x;

Example 2: WAP to explain the use of Explicit conversion.

void main()
{
    int a=10, b=4;
    float c;
    clrscr();
    c=(float)a/b; //explicit conversion: convert a into float then put result in c.
    cout<<"After Explicit Conversion = %f"<<c;
    getch();
}
After Explicit Conversion = 2.500000

C Language Feedback, Questions, Suggestions, Discussion.