< Prev
Next >

# C++ Type Cast Operator

C++ provides us a type-cast operator which allows us to explicit cast the value of a variable or value of an expression. Before we understand what exactly a type-cast operator is about, we need to understand a few important rules, which says -

• The result of an operation between any two or more primitive integral(non-decimal) data-type always results in integral data-type value.

• The result of an operation between any two or moreprimitivefloating data-type always results in floating data-type value.

• The result of an operation between aprimitiveintegral data-type and a floating primitive data-type always results in floating data-type value.

To understand the rule we have just explained, let us see an example.

``````#include<iostream>

using namespace std;

int main()
{
int a = 10, b =3;

//An expression involving two int variables a and b
float result = a/b;

cout << "The result of dividing 10/3 is : " << div;
}``````

## Output

``The value of dividing 10/3 is : 3``

According to the one of the rules we have just explained- "The result of an operation between any two or more primitive integral(non-decimal) data-type always results in integral data-type value", hence in the program above, the result of an expression involving two int variables a and b resulted in an int value i.e. 3, even though we expected the result to be in a decimal point float value.

Hence, in such scenarios we need to use type-cast operator to explicit cast the value of an expression from a data-type to another data-type of our choice.

## Using type-cast operator

The type-cast operator is used to explicitly cast the value of an expression from one data-type to another data-type. In order to use the type-cast operator, let us see its syntax - ``````#include<iostream>

using namespace std;

int main()
{
int a = 10, b =3;

//An expression involving two int variables a and b
float result = (float)a/b;

cout << "The result of dividing 10/3 is : " << result;
}``````

## Output

``The result of dividing 10/3 is : 3.33333``

According to the rule - - "The result of an operation between any two or more primitive integral(non-decimal) data-type always results in integral data-type value", but in the program above, we have used the type-cast operator to cast the result between two int values to a float, resulting in a decimal point float value i.e. 3.3333.

< Prev
Next >
< Scope Resolution Operator
New Operator in C++ >   