Type Conversions & Casting in C++
🟢 Beginner
📖 Definition
Type casting converts a value from one data type to another. C++ provides compile-time safe explicit casting using static_cast<T>(expr) instead of unsafe C-style (T)expr casts.
💡 Code Example
#include <iostream>
int main() {
int totalScore = 95;
int totalCount = 10;
// static_cast forces floating-point division instead of integer division truncation
double average = static_cast<double>(totalScore) / totalCount;
std::cout << "Average Score: " << average << "\n";
return 0;
}
👀 Output
Average Score: 9.5