C++•Type Casting
C++ Type Casting: static_cast and Modern C++ Casts
Modern C++ replaces dangerous C-style (type)value casts with explicit keywords: static_cast, dynamic_cast, const_cast, and reinterpret_cast.
Syntax
target_type val = static_cast<target_type>(original_val);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| static_cast<T> | Cast Operator | Performs compile-time checked safe conversions. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C++ locally:
#include <iostream>
int main() {
double preciseValue = 9.8765;
int truncated = static_cast<int>(preciseValue);
std::cout << "Original Double: " << preciseValue << "\n";
std::cout << "static_cast<int>: " << truncated << "\n";
// Converting ASCII character to integer code
char symbol = 'C';
int asciiCode = static_cast<int>(symbol);
std::cout << "Character '" << symbol << "' ASCII code: " << asciiCode << "\n";
return 0;
}Expected Output:
Original Double: 9.8765 static_cast<int>: 9 Character 'C' ASCII code: 67
How It Works: Step-by-Step
- Line 5: Converts double to int with compile-time checked static_cast.
- Line 12: Casts character literal to its underlying ASCII numeric code.
Key Concepts
- static_cast verifies that types are convertible at compile time.
- C-style casts (int)val bypass type safety and are strongly discouraged in modern C++.
- static_cast prevents accidental pointer conversions that lead to undefined behavior.
Common Mistake: Using legacy C-style casts (int)val in C++
C-style casts silently allow dangerous conversions that static_cast would catch at compile time.
❌ Incorrect
int* p = (int*)3.14; // Unsafe C-style cast
✅ Correct
// static_cast refuses to compile illegal conversions int x = static_cast<int>(3.14);
Related C++ Tutorials & Compiler
C++ Variables and Primitive Data Types with Examples
Learn how to declare typed variables in C++ including int, double, char, bool, and auto.
C++ Operators: Arithmetic, Relational, and Bitwise
Master C++ arithmetic, comparison, logical, compound assignment, and bitwise operators.
C++ Input and Output: std::cin, std::cout, and getline
Learn how to read from stdin with std::cin and std::getline, and format output stream data.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.