cpp / beginner
Snippet
Static Cast: Safe Type Conversion
static_cast is a compile-time type conversion operator that performs basic type conversions safely. It checks for valid conversions at compile time, making bugs easier to catch. Here we convert an int to double, a double to int (truncating the decimal part), and a char to its ASCII integer value. This is safer than C-style casting and makes your intent clear to other developers.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>using namespace std;int main() {int wholeNumber = 42;double decimalNumber = 3.14;double convertedNum = static_cast<double>(wholeNumber);int convertedInt = static_cast<int>(decimalNumber);cout << "Integer to double: " << convertedNum << endl;cout << "Double to integer: " << convertedInt << endl;char letter = 'A';int asciiValue = static_cast<int>(letter);cout << "Char 'A' as integer: " << asciiValue << endl;return 0;}
Breakdown
1
static_cast<double>(wholeNumber)
Converts int wholeNumber to double - adds decimal part (.0)
2
static_cast<int>(decimalNumber)
Converts double to int - truncates (cuts off) the decimal part, result is 3
3
static_cast<int>(letter)
Converts char 'A' to its ASCII numeric value, which is 65
4
cout << "Double to integer: " << convertedInt
Prints 3 because .14 was truncated when converting 3.14 to int
5
cout << "Char 'A' as integer: " << asciiValue
Prints 65 because that's the ASCII code for uppercase A