Introduction:
Type Conversion in C++
In C++ programming language, we are provided with the functionality where we can convert any particular type into data of some other desired type. This functionality can be called type conversion.
Generally there are two types of type conversion in C++ programming language:-
- Implicit Conversion
- Explicit Conversion
Implicit Type Conversion in C++:
This is the type conversion which is performed by the compiler automatically, and it is called implicit type conversion. This type of conversion can also be called an automatic conversion.
Example for implicit Type Conversion in C++:
Type Conversion in C++
Output:
ri_num_int = 9
ri_num_double = 9
In the program there have been an assignment of an int data to a double variable.
Data loss during conversion:
Conversion from one data type to another can be prone to data loss. This is generally supposed to happen when data of larger size will get converted to data of smaller size.
Explicit Type Conversion in C++:
In the C++ programming language, when some user changes the type of one data to some other type then it can be called explicit type conversion. This type of conversion can also be called as type casting.
There are generally three different ways which can help us in explicit conversion in C++ programming language :
- C-style type casting (also known as cast notation)
- Function notation (also known as old C++ style type casting)
- Type conversion operators
C-style type casting:
The C programming language favours this style of casting. This can also be called as cast notation.
The syntax for this style is:
(data_type)expr;
For example,
type conversion in c++
Function-style type casting:
Function like notation can be used by us in order to perform casting.
The syntax for this style is:
data_type(expr);
For example,
Type Conversion in C++
Example of type casting :
Output:
ri_num_double = 3.56
ri_num_int1 = 3
ri_num_int2 = 3
From the above example we can see that the C-style type conversion as well as the function-style type conversion, both perform the same tasks and ultimately they produce the same results.
Type conversion in c++