C++ Data Types
The data type tells the compiler how much memory a variable needs and what operations are allowed.
Fundamental types
| Type | Keeps | Typical size |
|---|---|---|
| bool | true or false | 1 byte |
| char | One character (or a small number) | 1 byte |
| short | Small whole number | 2 bytes |
| int | Whole number | 4 bytes |
| long | Bigger whole number | 4 or 8 bytes |
| long long | Very big whole number | 8 bytes |
| float | Decimal, about 7 digits | 4 bytes |
| double | Decimal, about 15 digits | 8 bytes |
| long double | More precise decimal | 8, 12 or 16 bytes |
| void | No value (for functions) | none |
The sizes depend on the system. Ask the compiler:
#include <iostream>
#include <limits>
int main() {
std::cout << "bool: " << sizeof(bool) << '\n';
std::cout << "char: " << sizeof(char) << '\n';
std::cout << "short: " << sizeof(short) << '\n';
std::cout << "int: " << sizeof(int) << '\n';
std::cout << "long: " << sizeof(long) << '\n';
std::cout << "long long: " << sizeof(long long) << '\n';
std::cout << "float: " << sizeof(float) << '\n';
std::cout << "double: " << sizeof(double) << '\n';
std::cout << "int max: " << std::numeric_limits<int>::max() << '\n';
std::cout << "int min: " << std::numeric_limits<int>::min() << '\n';
std::cout << "double max: " << std::numeric_limits<double>::max() << '\n';
}
bool: 1
char: 1
short: 2
int: 4
long: 8
long long: 8
float: 4
double: 8
int max: 2147483647
int min: -2147483648
double max: 1.79769e+308
This output is from a 64 bit Linux system. On Windows long is 4 bytes.
signed and unsigned
Integer types are signed by default (can be negative). With unsigned they keep only zero and positive numbers, with a bigger maximum. Overflow of an unsigned number wraps around, and overflow of a signed number is undefined behavior.
#include <iostream>
int main() {
unsigned int u = 0;
u = u - 1; // wraps to the biggest value
std::cout << u << '\n';
unsigned char c = 255;
c = c + 1;
std::cout << static_cast<int>(c) << '\n';
}
4294967295
0
Fixed width types
When you need an exact size, use <cstdint>:
#include <cstdint>
#include <iostream>
int main() {
std::int8_t a = 100;
std::uint16_t b = 65535;
std::int64_t c = 9'000'000'000'000; // ' makes long numbers easy to read
std::cout << static_cast<int>(a) << " " << b << " " << c << '\n';
std::cout << sizeof(std::int32_t) << " " << sizeof(std::uint64_t) << '\n';
}
100 65535 9000000000000
4 8
char is a number too
#include <iostream>
int main() {
char c = 'A';
std::cout << c << " " << static_cast<int>(c) << " " << static_cast<char>(c + 1) << '\n';
}
A 65 B
Decimals are not exact
#include <iomanip>
#include <iostream>
int main() {
std::cout << std::setprecision(17) << 0.1 + 0.2 << '\n';
std::cout << (0.1 + 0.2 == 0.3) << '\n';
}
0.30000000000000004
0
Never compare decimals with ==. Compare the difference with a small number (epsilon).
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |