Type Conversion in C++

Type Conversion means conversion of one data-type to another data-type. In C Plus Plus (C++), type conversion can be done by two ways:

  1. Automatic Conversion
  2. Type Casting

1) Automatic Conversion:
In C++, if we have mixed mode expression (i.e., different types of data in one expression) then the lower data-type variable is automatically converted to the data-type of the higher data-type variable.

Let us illustrate this with am example as follows:

In the above example, in expression:

firstly, variable c of the type int is converted to type float and is stored in a temporary variable before being multiplied by variable a of type float. Also, the result of multiplication c * a which comes in type float is then converted to type double and then is assigned to variable t of type double.

2) Type Casting
The casting is a technique by which forcefully we can convert one data-type to other data-type. The operator used for this purpose is known as cast operator.

The cast operator takes on any of the following format:
(cast-type) expression;
cast-type (expression);

Where cast-type refers to the data-type to which we desire to convert the expression to, and expression is any valid C++ expression or it may be a single variable.

Example of Type Casting:

In the above example, variable a is converted into float data-type before getting multiplied by variable b because of the use of the cast operator in the expression ((float) a).

You may also like...

Leave a Reply

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