capypad
0 day streak
cpp / beginner
Snippet

Type Casting: Converting Between Data Types

Type casting converts a value from one data type to another. C++ provides static_cast for compile-time type conversions between related types like numbers and characters. When casting a double to an int, the decimal portion is truncated (not rounded). When casting an int to a double, the value remains the same but gains a decimal point. Casting a char to an int reveals its ASCII numeric value, where 'A' equals 65.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
 
int main() {
int wholeNumber = 42;
double pi = 3.14159;
double fromInt = static_cast<double>(wholeNumber);
int fromDouble = static_cast<int>(pi);
std::cout << "Integer as double: " << fromInt << std::endl;
std::cout << "Double as integer: " << fromDouble << std::endl;
char letter = 'A';
int asInt = static_cast<int>(letter);
std::cout << "Char 'A' as integer: " << asInt << std::endl;
return 0;
}
Breakdown
1
int wholeNumber = 42;
Integer variable with value 42
2
double pi = 3.14159;
Double variable with decimal value
3
double fromInt = static_cast<double>(wholeNumber);
Converts int to double, result is 42.0
4
int fromDouble = static_cast<int>(pi);
Converts double to int, truncates to 3
5
std::cout << "Integer as double: " << fromInt << std::endl;
Prints converted double value
6
std::cout << "Double as integer: " << fromDouble << std::endl;
Prints truncated integer value
7
char letter = 'A';
Character variable holding letter A
8
int asInt = static_cast<int>(letter);
Converts char to its ASCII numeric value
9
std::cout << "Char 'A' as integer: " << asInt << std::endl;
Prints ASCII value 65