0 day streak
cpp / intermediate
Snippet

Explicit Narrowing Conversions

Using static_cast for type conversion is preferred over C-style casts because it is more visible in the code and checked by the compiler. It signals to other developers that the precision loss during conversion is intentional.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
int main() {
double precisionValue = 42.997;
// static_cast is the safe way to perform explicit type conversion
int wholeNumber = static_cast<int>(precisionValue);
std::cout << "Precise: " << precisionValue << "\n";
std::cout << "Integer: " << wholeNumber << std::endl;
return 0;
}
Breakdown
1
int wholeNumber = static_cast<int>(precisionValue);
Explicitly converts a double to an int, truncating the decimal part.