Type Conversion In C++





Type Conversion In C++

This process of converting one predefined type into another is called type conversion.

When constants and variables of different types are mixed in an expression, they are converted to the same type.

C++ facilitated the type conversion in two forms:-

Implicit type conversion (automatic conversion):-

It is a conversion performed by the compiler automatically. This conversion takes place when two operands of different types are encountered to the type of the higher type variable.
Since all operand are converted up to the type of the largest type operand it is called type promotion.

E.g.

#include<iostream.h>
#include<conio.h>
Void main ()
{
Int a=7;
Float b=155.5;
Double c=a*b;
Cout<<”\n the value of c :”<< c;
getch ();
}

Here a variable of type int is multiplied by variable of type float to yield a result of type double.

Explicit type conversion (casts):-

It is user defined conversion that forces an expression to be of specific type. It is applied when a programmer needs to convert a value from one type to another. This conversion is also called type casting and it is done using type_cast operator. i.e. () that is used as:-

(Type) expression

Where type is a valid c++ data type to which the conversion is to be done.

To determine the use of the cast operator, let us consider the following example.

Char ch;
Float abc;
Int x, y, z;
x= (int) ch;

Where ch is a character variable and force to convert as the integer data type.

abc= (float) (y*z);

Where the expression (y*z) is an integer data type and force to covert as a floating point number.



Related posts:

  1. Predefined Data Types Predefined data types Data can be of many types (e.g....
  2. Implicit and explicit functions What is Implicit and Explicit function? Continue reading to find...
  3. Object oriented programming Object oriented programming : The main idea behind object oriented...
  4. Integration by Substitution Integration by substitution , how to integrate a integral by...
  5. Procedural oriented programming Procedural oriented programming (pop):- A program in a procedural language...