C++ Data Types
A data type is the kind of value a variable holds. Each type stores its own kind of value and takes its own amount of space.
One value of each type
Three variables hold three kinds of value. Each print line shows one value.
#include <iostream>
int main() {
int count = 42;
double price = 3.5;
char grade = 'A';
std::cout << count << "\n";
std::cout << price << "\n";
std::cout << grade << "\n";
return 0;
}Sizes with sizeof
A byte is a small unit of storage. sizeof tells how many bytes a type takes.
#include <iostream>
int main() {
std::cout << sizeof(int) << "\n";
std::cout << sizeof(double) << "\n";
return 0;
}A large whole number
A long long variable holds a large whole number. The number prints whole, with no part cut off.
#include <iostream>
int main() {
long long distance = 1234567890123;
std::cout << distance << "\n";
return 0;
}Example
#include <iostream>
int main() {
int age = 30;
double height = 1.8;
char initial = 'B';
std::cout << "int: " << age << "\n";
std::cout << "double: " << height << "\n";
std::cout << "char: " << initial << "\n";
return 0;
}Key points
- The int type holds whole numbers.
- The double type holds decimal numbers.
- The float type holds decimal numbers and takes less space than double.
- The char type holds one character.
- The bool type holds true or false.
- The std::string type holds text.
- The long long type holds whole numbers larger than int can hold.
In this example, age holds the int value 30. height holds the double value 1.8. initial holds the char value B. Each print line pairs a type name with its value.
Note
The sizeof tool tells the size of a type.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C++ Compiler
C++ data types
| Type | Holds | Example |
|---|---|---|
| int | Whole numbers | 42 |
| double | Decimal numbers | 3.5 |
| float | Decimal numbers | 1.5 |
| char | One character | 'A' |
| bool | True or false | true |
| std::string | Text | "Hello" |
| long long | Large whole numbers | 1234567890123 |
Exercise
Which type holds one character?