In this tutorial you will learn about the C++ Type Conversion and its application with practical example.
C++ Type Conversion
C++ is a strong-typed language, which mean have associated data type with a variable before it is being used in program. Type conversion is basically way to convert an expression of a given type into another type. When a variable is converted into a different type, the compiler basically treats the variable as of the new data type. In C++, there are two types of type conversion –
Type of Conversion
- implicit conversion
- explicit conversion
Implicit Conversion
In implicit or automatic conversion compiler will automatically change one type of data into another. For instance, if you assign an integer value to a floating-point variable, the compiler will insert code to convert the int to a float.
Example:-
1 2 3 |
short a=2000; int b; b=a; |
Here value of 'a' has been promoted from short to int and we have not had to specify any type-casting operator. implicit conversions affect fundamental data types. Typecasting should always be used in right order (low to higher datatype).Typecasting in wrong places may result in loss of precision, which the compiler can signal with a warning. for example like for instance truncating a float when typecasting to an int.This can be avoided with an explicit conversion. Below is the right order for numerical conversion.
short int -> int -> unsigned int ->long int -> unsigned long int -> float -> double -> long double
Explicit Conversion
It allows you to make this type conversion explicit, or to force it when it wouldn’t normally happen.To perform type casting, put the desired type including modifiers (like double) inside parentheses to the left of the variable or constant you want to cast. In C++, there are two ways we can perform generic type casting –
Syntax 1:-
1 |
type (expression) //functional casting |
Example:-
1 2 3 |
double x = 10.3; int y; y = int (x); // functional notation |
Syntax 2:-
1 |
(type) expression //c-like casting |
Example:-
1 2 3 |
double x = 10.3; int y; y = (int) x; // c-like cast notation |