Type casting helps you change a value from one type to another. It is useful when you want to treat data differently or avoid errors.
0
0
Type casting in C++
Introduction
When you want to convert a floating-point number to an integer to remove decimals.
When you need to treat a number as a different type to perform specific operations.
When you want to convert between compatible pointer types.
When you want to force a conversion that the compiler does not do automatically.
When you want to make your intentions clear to other programmers reading your code.
Syntax
C++
type new_variable = (type) old_variable; // C-style cast new_variable = static_cast<type>(old_variable); // C++ style cast
C++ prefers static_cast because it is safer and clearer.
C-style casts can do many conversions but are less safe and harder to find in code.
Examples
This converts integer
a to double using C-style cast.C++
int a = 10; double b = (double) a;
This converts double
x to int using static_cast, dropping decimals.C++
double x = 9.7; int y = static_cast<int>(x);
This converts character
c to its ASCII integer value.C++
char c = 'A'; int ascii = static_cast<int>(c);
Sample Program
This program shows how to convert a double to an int and a char to its ASCII integer value using static_cast.
C++
#include <iostream> int main() { double pi = 3.14159; int intPi = static_cast<int>(pi); // convert double to int std::cout << "Original double: " << pi << "\n"; std::cout << "After casting to int: " << intPi << "\n"; char letter = 'Z'; int asciiValue = static_cast<int>(letter); // char to int std::cout << "Character: " << letter << " has ASCII value: " << asciiValue << "\n"; return 0; }
OutputSuccess
Important Notes
When casting from floating-point to integer, the decimal part is dropped, not rounded.
Use static_cast for most conversions to keep code clear and safe.
Be careful when casting pointers; improper casts can cause crashes.
Summary
Type casting changes a value from one type to another.
Use static_cast in C++ for safe and clear conversions.
Casting helps avoid errors and makes your code intentions clear.