capypad
0 day streak
cpp / beginner
Snippet

Type Conversion with static_cast

static_cast is used to convert one type to another in a safe, explicit way. When you cast a double to an int, the decimal part is lost. When casting int division to double, you get accurate results. Using static_cast makes your intention clear and helps catch errors.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
 
int main() {
double pi = 3.14159;
int wholeNumber = static_cast<int>(pi);
cout << "Pi as double: " << pi << endl;
cout << "Pi as int: " << wholeNumber << endl;
int a = 10, b = 3;
double division = static_cast<double>(a) / b;
cout << "10 / 3 = " << division << endl;
char c = static_cast<char>(65);
cout << "65 as char: " << c << endl;
return 0;
}
Breakdown
1
static_cast<int>(pi)
Converts double pi to integer, truncating decimals
2
static_cast<double>(a) / b
Converts a to double before division for precise result
3
static_cast<char>(65)
Converts integer 65 to its ASCII character 'A'
4
wholeNumber
Stores the truncated integer value