🔄 C++ Type Casting – Convert One Type to Another
Sometimes in C++, you need to change one data type into another. This is called type casting — like telling your program, “Hey, treat this float like an int!”
🎭 Types of Type Casting
- Implicit Casting (automatic): Done by the compiler
- Explicit Casting (manual): Done by the programmer
🧪 Example: Implicit Type Casting
In this example, C++ automatically converts an int
to a float
.
#include <iostream> using namespace std; int main() { int num = 10; float result = num; // int is implicitly cast to float cout << "Result: " << result << endl; return 0; }
✋ Example: Explicit Type Casting
You can forcefully convert one type to another using (type)
before the value.
#include <iostream> using namespace std; int main() { float pi = 3.14159; int approx = (int) pi; // Explicit cast cout << "Original: " << pi << endl; cout << "After Casting: " << approx << endl; return 0; }
📘 C++ Style Casting (Best Practice)
You can also use C++-style casting, which is more readable and type-safe:
static_cast<type>(expression)
– For most general conversions
🔍 Example: static_cast
#include <iostream> using namespace std; int main() { double money = 99.99; int rupees = static_cast<int>(money); cout << "Money: " << money << endl; cout << "Rupees (int): " << rupees << endl; return 0; }
🧠 Remember
- Implicit casting happens automatically (no code needed)
- Explicit casting requires your command (like
(int)
orstatic_cast
) - Use
static_cast
for modern and safe C++ code