The Program in C++ to Test the Type Casting is given below:
#include <iostream>
int main() {
int a;
double b;
std::cout << "Enter an integer: ";
std::cin >> a;
std::cout << "Enter a double: ";
std::cin >> b;
// Implicit type casting
double c = a + b; // a is implicitly cast to double
std::cout << "Implicit type casting: " << c << std::endl;
// Explicit type casting
int d = (int)(a + b); // a + b is explicitly cast to int
std::cout << "Explicit type casting: " << d << std::endl;
return 0;
}
Output:
Enter an integer: 56
Enter a double: 12
Implicit type casting: 168
Explicit type casting: 168
Pro-Tips💡
This code uses the cin
function to read input from the user and store it in the variables a
and b
.
Then, the code performs the same type casting operations as the previous example, but using the user-provided values for a
and b
.
The first operation demonstrates implicit type casting, which is when the compiler automatically converts one data type to another without the programmer explicitly requesting the conversion.
In this case, the value of a
is implicitly cast to a double
when it is added to the value of b
, and the result is stored in the variable c
.
The second operation demonstrates explicit type casting, which is when the programmer explicitly requests a conversion using the (type)
notation.
In this case, the result of the expression a + b
is explicitly cast to an int
and stored in the variable d
.
As the output, it will show the results of the Implicit type casting and the Explicit type casting.
It’s important to note that casting can cause data loss if the target data type is not able to represent the value of the original data type.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.