capypad
0 day streak
cpp / beginner
Snippet

Type Casting: Converting Between Types

Type casting converts a value from one data type to another. Explicit casting using (type)value forces conversion. When dividing integers, the result is integer division (truncates decimals). Casting one operand to double ensures floating-point division. This is essential for controlling how C++ interprets your values.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;
 
int main() {
int whole = 10;
int other = 3;
double result1 = whole / other;
double result2 = (double)whole / other;
cout << "Ganzzahl-Division: " << result1 << endl;
cout << "Mit Casting: " << result2 << endl;
char letter = 'A';
int ascii = (int)letter;
cout << "Buchstabe 'A' als Zahl: " << ascii << endl;
double pi = 3.14159;
int truncated = (int)pi;
cout << "Gerundet: " << truncated << endl;
return 0;
}
Breakdown
1
double result1 = whole / other;
Integer division: 10 / 3 = 3 (decimal part lost)
2
(double)whole / other
Casts 'whole' to double before division, resulting in 3.333...
3
(int)letter
Converts character 'A' to its ASCII numeric value 65
4
(int)pi
Casts double to int, truncating decimal portion (3.14159 becomes 3)