C++ Type Casting
Type casting in C++ allows us to convert one data type to another. This is sometimes necessary when working with different data types in a program. There are two types of type casting in C++, implicit and explicit.
Syntax
Implicit type casting:
data_type_1 var1 = value;
data_type_2 var2 = var1;
Explicit type casting:
(data_type) expression
Example
Implicit type casting:
#include <iostream>
using namespace std;
int main() {
int num1 = 10;
float num2 = num1;
cout << "num1: " << num1 << endl;
cout << "num2: " << num2 << endl;
return 0;
}
Explicit type casting:
#include <iostream>
using namespace std;
int main() {
float num1 = 10.5;
int num2 = (int)num1;
cout << "num1: " << num1 << endl;
cout << "num2: " << num2 << endl;
return 0;
}
Output
Implicit type casting:
num1: 10
num2: 10
Explicit type casting:
num1: 10.5
num2: 10
Explanation
In the first example, we are converting an int data type to a float data type using implicit type casting. The compiler automatically converts the int to a float when assigning the value of num1 to num2.
In the second example, we are converting a float data type to an int data type using explicit type casting. By enclosing the expression num1 in parentheses with the int data type, we are telling the compiler to convert num1 to an int.
Use
Type casting can be useful when working with different data types in a program. You may need to cast a data type to another to perform arithmetic operations or to compare data. For example, you may need to cast a float to an int when working with a loop that requires an integer value.
Important Points
- Implicit type casting happens automatically in C++.
- Explicit type casting involves using a cast operator to convert one data type to another.
- Type casting can be useful when working with different data types in a program.
Summary
Type casting in C++ allows us to convert one data type to another. Implicit type casting happens automatically while explicit type casting involves using a cast operator to convert one data type to another. Type casting can be useful when working with different data types in a program.