Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

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

TypeHoldsExample
intwhole numbers42
long longbig whole numbers9000000000LL
doublenumbers with a decimal point (about 15 digits)3.14
floatdecimals with less precision (about 7 digits)3.14f
charone character'A'
booltrue or falsetrue
std::stringtext (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;
}
Output
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;
}
Output
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;
}
Output
A has code 65
next: B

Practice exercises

  1. Print the sizes of short, long, float and char.
  2. Store the world population (about 8000000000) in a fitting type and print it.
  3. Print the largest value an unsigned int can hold using numeric_limits.