Topic 12 of 83
Type Casting
Overview
Type casting converts a variable from one data type to another. Implicit casting happens automatically, while explicit casting is forced by the programmer.
Syntax
cpp
// Implicit Casting (Automatic type promotion)
int a = 5;
double b = a; // Automatically promoted to 5.0
// Explicit Casting (C-style)
double pi = 3.14;
int approxPi = (int)pi; // Truncates to 3
// Explicit Casting (C++ style - Preferred)
int cppCast = static_cast<int>(pi);Common Pitfalls
- Data loss during casting (e.g., casting a `double` to an `int` discards the decimal portion; casting a large `long` to a `short` overflows).
Interview Tips
- Explain why C++ style casts (`static_cast`, `dynamic_cast`, `reinterpret_cast`) are preferred over C-style casts. They are easier to search for in code and checked by the compiler more strictly.
Real-World Example
Casting to achieve accurate floating-point division.
example
cpp
#include <iostream>
using namespace std;
int main() {
int totalScore = 15;
int subjects = 4;
// Without cast, 15/4 = 3
// With static_cast, 15.0/4 = 3.75
double average = static_cast<double>(totalScore) / subjects;
cout << "Average: " << average << "\n";
return 0;
}