0 Tage Serie
cpp / intermediate
Snippet

Explizite verengende Konvertierungen

Die Verwendung von static_cast für die Typumwandlung wird gegenüber C-Style-Casts bevorzugt, da es im Code besser sichtbar ist und vom Compiler geprüft wird. Es signalisiert anderen Entwicklern, dass der Präzisionsverlust bei der Umwandlung beabsichtigt ist.

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;
}
Erklärung
1
int wholeNumber = static_cast<int>(precisionValue);
Konvertiert explizit ein Double in ein Int, wobei der Nachkommateil abgeschnitten wird.