The data type of any variable tells us about the value you can store in that variable and what operations you can perform on it. It might be possible that one operation is supported by more than one data type and to handle such cases C++ allows us to convert one datatype to another datatype. This process of converting data type is known as Type Conversion or Type Casting.
In C++, there are two types of Type Conversion:
- Implicit Type Conversion.
- Explicit Type Conversion.
Implicit Type Conversion in C++.
Let's understand with some examples of implicit type conversion.
//Example of Implicit Type Conversion #include<iostream> using namespace std; int main(){ //conversion of int to bool type int value = 25; bool check = value; cout<<check<<endl; //conversion of double to int double pi = 3.14; int i = pi; cout<<i<<endl; //conversion of signed to unsigned unsigned int num = -1; cout<<num<<endl; return 0; }
1
3
4294967295
- When we assign one of the non-boolean arithmetic types to a boolean object, the result is false if the value is 0 and true otherwise.
- When we assign a boolean to one of the arithmetic types, the result value is 1 if the boolean is true and 0 if the boolean is false.
- When we assign a floating-point value to an object of integral type, the value is truncated. It means the value before the decimal point will get stored.
- When we assign an integral value to a floating type then the fraction part is zero.
- When we assign a signed value to an unsigned value then it stores 2's complement of the value.
Explicit Type Conversion in C++.
- Forceful Casting: In this type of casting you explicitly define the required datatype in front of the expression.
//Example of Explicit Type Conversion #include<iostream> using namespace std; int main(){ float x = 3.14; int ans = (int)x * 4 * 4; cout<<ans<<endl; return 0; }
48
Type Conversion Operators
- Static cast
- Dynamic cast
- Const cast
- Reinterpret cast
//C++ Example of Operator Type Conversion #include<iostream> using namespace std; int main(){ float x = 3.14; int ans = static_cast<int>(x); cout<<ans<<endl; return 0; }
3
No comments:
Post a Comment