C++ Data Conversion

There are two type data conversions:

1. Implicit Conversion

  • Implicit conversion means automatic conversion
  • The output of arithmetic expression is converted automatically into particular data type.
  • The output expression will be of higher number of bytes and range in data type.

Rules Of Implicit Conversion:


Operand 1 Operan 2 Output
short short short
short int int
short long long
short float float
short double double
short char short

Program To Show Implicit Conversion



#include<iostream.h>
#include<conio.h>
void main()
{
      clrscr();
      int x,y,z;
      float a,b;
      x=10;
      y=3;
      z=x/y;
      cout<<"\nz="<<z;
      a=x/y;
      cout<<"\na="<<a;
      b=x/a;
      cout<<"\nb="<<b;
      z=x/a;
      cout<<"\nz="<<z;
      getch();
}

Output


z=3
a=3
b=3.3333
z=3



2. Explicit Conversion / Casting


  • This is also known as Casting
  • To convert the output of arithmetic expression into data type specified by the programmer.
  • Used to change implicit conversion

Syntax


(type)Expression  OR type(Expression)


Here, type refers to data type.

Expression refers to arithmetic expression.


Program to show use of Explicit Conversion



#include<iostream.h>
#include<conio.h>
void main()
{
      clrscr();
      int a,b;
      float c;
      a=10;
      b=3;
      c=a/(float)b;
      cout<<"\nc="<<c;
      getch();
}



Output


c=3.3333

Back To Top