C++ Data Types and auto
Every value in C++ has a type. The type decides how much memory the value uses, which values it can hold and what you can do with it.
The basic types
| Type | Holds | Example |
|---|---|---|
int | whole numbers | 42 |
long long | big whole numbers | 9000000000LL |
double | numbers with a decimal point (about 15 digits) | 3.14 |
float | decimals with less precision (about 7 digits) | 3.14f |
char | one character | 'A' |
bool | true or false | true |
std::string | text (from the string header) | "Hello" |
Use int for whole numbers, double for decimals and std::string for text unless you have a reason to choose another type.
Sizes and limits
sizeof gives the size of a type in bytes. std::numeric_limits from the limits header gives the smallest and largest values.
#include <iostream>
#include <limits>
int main() {
std::cout << "int: " << sizeof(int) << " bytes, up to "
<< std::numeric_limits<int>::max() << "\n";
std::cout << "long long: " << sizeof(long long) << " bytes, up to "
<< std::numeric_limits<long long>::max() << "\n";
std::cout << "double: " << sizeof(double) << " bytes\n";
std::cout << "bool: " << sizeof(bool) << " byte\n";
return 0;
}int: 4 bytes, up to 2147483647 long long: 8 bytes, up to 9223372036854775807 double: 8 bytes bool: 1 byte
Sizes can differ between computers; that is why sizeof exists. Going past the largest value of a signed integer type is overflow, a bug with no defined result, so choose a big enough type.
auto
auto lets the compiler work out a variable's type from its value:
#include <iostream>
#include <string>
int main() {
auto count = 10; // int
auto price = 4.5; // double
auto letter = 'x'; // char
auto name = std::string("Ravi");
std::cout << count << " " << price << " " << letter << " " << name << "\n";
return 0;
}10 4.5 x Ravi
auto is most useful for long type names, such as the iterators of the STL. For simple variables, writing the type yourself often makes the code clearer. Note that auto s = "text"; gives a pointer to characters, not a std::string.
Characters are small numbers
A char holds a character's code: 'A' is 65. Converting with static_cast<int>(c) shows the number; adding to a char gives the next character.
#include <iostream>
int main() {
char c = 'A';
std::cout << c << " has code " << static_cast<int>(c) << "\n";
std::cout << "next: " << static_cast<char>(c + 1) << "\n";
return 0;
}A has code 65 next: B
Practice exercises
- Print the sizes of
short,long,floatandchar. - Store the world population (about 8000000000) in a fitting type and print it.
- Print the largest value an
unsigned intcan hold usingnumeric_limits.