Skip to content
Theory · Variables and Types · lesson 1 of 10

Built-in types and their sizes

A C++ program keeps data in variables, and every variable has a type. The type is set in the declaration: it decides which values the variable holds and how they are printed. Here true is printed as 1:

C++
#include <iostream>

int main() {
    int count = 3;
    double price = 2.5;
    char grade = 'A';
    bool ready = true;
    std::cout << count << ' ' << price << '\n';  // 3 2.5
    std::cout << grade << ' ' << ready << '\n';  // A 1
}

The declaration int count = 3; creates a variable, a named place in memory. Its type is int, its name is count, and its initial value is 3. From then on, the name stands for the value: std::cout << count prints 3. A variable's type does not change after the declaration.

Basic types

Four types appear in almost every program:

  • int: a whole number, such as 42, -7 or 0;
  • double: a number with a fractional part, such as 2.5 or -0.1;
  • char: a single character in single quotes, such as 'A' or '7';
  • bool: a logical value, true or false; std::cout prints them as 1 and 0.

Two more types are needed less often. long long holds whole numbers too large for an int, and float holds fractional numbers with less precision than a double. The integer types short and long exist too: a short is no wider than an int, and a long is no narrower.

Size in bytes

Each type takes a fixed number of bytes in memory, and that number limits which values fit in a variable. sizeof shows the size. The C++ standard fixes only sizeof(char), which is always 1. The other sizes depend on the platform and the compiler:

C++
#include <iostream>

int main() {
    std::cout << sizeof(char) << ' ' << sizeof(int) << '\n';  // 1 4
    std::cout << sizeof(long long) << ' ' << sizeof(double) << '\n';  // 8 8
}

This is what the program prints on a typical computer and in the course exercises. A 4-byte int holds numbers up to about two billion, and larger ones go in a long long.

The type of a literal

A literal is a value written directly in the code. The compiler tells its type from the way it is written:

LiteralType
10int
2.5double
2.5ffloat
'a'char
truebool

A number with a decimal point is a double, even without a fractional part: 2.0 is a double too. The suffix f makes the literal a float: 2.5f is a float, not a double. sizeof shows the difference:

C++
std::cout << sizeof(2.5) << ' ' << sizeof(2.5f) << '\n';  // 8 4

Common mistake

A character is written in double quotes:

C++
char grade = "A";  // ✗
TEXT
error: cannot initialize a variable of type 'char' with an lvalue of type 'const char[2]'

This is a compile error. Double quotes create text of any number of characters, while a char holds exactly one. A single character goes in single quotes: 'A'.