Type casting is the process of converting data from one type to another. When a variable is typecast to a new data type, the compiler treats it as a new data type. There are two kinds of Type Casting Operators available in C++.
- Implicit type casting
- Explicit type casting
1. Implicit Type Casting
When data is used in expressions, the compiler automatically changes it from one type to another via implicit type casting. The compiler implicitly changes a value of one type to the value of the new type when it is assigned to another type.
For Example:
int x = 3.14156; //implicit casting to integer value 3
#include <iostream> using namespace std; int main() { int x = 3.14156; // Implicit conversion from double to int cout << "Type will implicitly change here: " << x; // Displaying the value of x return 0; }
OUTPUT OF THE PROGRAM:
Type will implicitly change here: 3
2. Explicit Type Casting
Explicit conversion of explicit type casting occurs when a user manually changes data from one type to another.
There are various ways to convert one type to another in C++, but the easiest is to use the new type enclosed in parentheses ()
before the expression to be converted.
Example: C++ Program To Demonstrate The Concept of Explicit Type Casting
#include <iostream> using namespace std; int main() { // Declare variables int x; float pi = 3.14; // Explicitly cast float to int x = int(pi); // Output the result cout << "Type will implicitly change here: " << x; return 0; }
OUTPUT OF THE PROGRAM:
Type will implicitly change here:: 3
In the above code, the float number 3.14
is converted to an integer value 3,
and the remainder (.14)
is discarded. Here, the type-casting operator is (int)
.