Data Types

Data Types in C++: Imagine packing a kitchen. You would not store soup in a paper bag or a single grain of rice in a wheelie bin.

The Analogy: Choosing the Right Container

Imagine packing a kitchen. You would not store soup in a paper bag or a single grain of rice in a wheelie bin. You pick a container that fits what you are storing: a small jar for spices, a large tub for flour, a sealed bottle for liquid.

C++ types are exactly that decision, made explicit. Every type is a promise about three things: how many bytes it occupies, what range of values it can hold, and what operations make sense on it. Unlike Python or JavaScript, where a number is just "a number", C++ makes you choose the container — and then holds you to it.

That sounds like extra work. In exchange you get speed (the compiler knows exactly how much memory to reserve) and safety (mixing incompatible types is a compile error, not a runtime surprise).


Syntax or Core Structure

#include <iostream>
#include <string>

int main() {
    // Integers
    int score{42};              // whole numbers, usually 4 bytes
    long long big{9000000000};  // when int is not wide enough
    unsigned int lives{3};      // no negatives, double the positive range
    short small{100};           // smaller footprint, rarely worth it

    // Floating point
    float ratio{0.5f};          // ~7 digits of precision, note the f suffix
    double precise{0.1};        // ~15 digits -- the default choice

    // Single characters
    char grade{'A'};            // one byte, single quotes

    // Truth values
    bool passed{true};          // true or false, 1 byte

    // Text
    std::string name{"Ada"};    // from <string>, double quotes

    std::cout << score << " " << ratio << " " << grade << " " << passed << "\n";
    return 0;
}

Two details that catch people out immediately: 'A' with single quotes is a char, while "A" with double quotes is a string. And std::cout << passed prints 1, not true — booleans print as integers unless you ask otherwise with std::boolalpha.


Technical Depth: Sizes, Ranges and Overflow

The standard does not fix exact sizes; it fixes minimums. On virtually every desktop and server compiler today you get:

TypeTypical sizeApproximate rangeUse it for
bool1 bytetrue / falseflags, conditions
char1 byte-128 to 127single characters, raw bytes
short2 bytes-32,768 to 32,767rarely needed
int4 bytesabout +/- 2.1 billiondefault whole number
long long8 bytesabout +/- 9.2 quintillionids, timestamps, big counts
unsigned int4 bytes0 to about 4.2 billionsizes, indices, bit patterns
float4 bytes~7 significant digitshuge arrays where memory matters
double8 bytes~15 significant digitsdefault real number

Ask the compiler rather than trusting a table:

#include <iostream>
#include <limits>

std::cout << sizeof(int) << " bytes\n";                       // 4 on most systems
std::cout << std::numeric_limits<int>::max() << "\n";         // 2147483647
std::cout << std::numeric_limits<double>::digits10 << "\n";   // 15

Overflow is not an error

int big{2147483647};   // the maximum int
big = big + 1;         // undefined behaviour -- typically wraps to -2147483648

unsigned int u{0};
u = u - 1;             // WELL defined, and wraps to 4294967295

Signed overflow is undefined behaviour: the compiler may assume it never happens and optimise accordingly, so the result can be genuinely unpredictable. Unsigned overflow is defined to wrap around, which is why for (unsigned i = size - 1; i >= 0; --i) is an infinite loop — an unsigned value is never negative.

Floating point does not store decimals exactly

double a{0.1}, b{0.2};
std::cout << (a + b == 0.3) << "\n";   // prints 0 -- they are NOT equal

// Compare with a tolerance instead
#include <cmath>
bool same = std::abs((a + b) - 0.3) < 1e-9;   // true

0.1 in binary is a repeating fraction, exactly like 1/3 in decimal. It gets rounded, and the rounding errors accumulate. Never use == on double. Never store money in a double — use integer cents, or a decimal library.

Conversions happen silently

double price{9.99};
int rounded = price;          // 9 -- the fraction is DISCARDED, not rounded
int half = 7 / 2;            // 3 -- integer division, the .5 never existed
double proper = 7 / 2.0;     // 3.5 -- one operand is double, so both are

int narrowed{price};         // COMPILE ERROR: braces reject narrowing. Good.

Integer division is the single most common silent bug in beginner C++. If either operand is floating point, the whole expression is; if both are integers, the result is truncated toward zero.


Real World Example: A Sensor Reading

#include <iostream>
#include <iomanip>
#include <string>

int main() {
    const std::string sensorId{"TEMP-07"};   // text: string
    const bool online{true};                 // yes/no: bool
    const int sampleCount{1440};             // whole count: int
    const long long unixTime{1735689600LL};  // too big for int: long long
    const double celsius{21.4567};           // real measurement: double
    const char unit{'C'};                    // one character: char

    const double fahrenheit = celsius * 9.0 / 5.0 + 32.0;   // 9.0 keeps it floating point

    std::cout << std::boolalpha;                    // print bools as true/false
    std::cout << std::fixed << std::setprecision(2); // two decimal places

    std::cout << "Sensor:  " << sensorId << "\n";
    std::cout << "Online:  " << online << "\n";
    std::cout << "Samples: " << sampleCount << "\n";
    std::cout << "Epoch:   " << unixTime << "\n";
    std::cout << "Reading: " << celsius << unit << " (" << fahrenheit << "F)\n";
    return 0;
}

Every type here was chosen for a reason. unixTime needs long long because seconds since 1970 already exceed the range of a 4-byte int for far-future dates and will overflow in 2038. The conversion uses 9.0 / 5.0 rather than 9 / 5 — the latter is integer division and would give 1, silently ruining the maths. std::setprecision from <iomanip> controls display only; the stored double keeps its full precision.


Common Mistakes

  • Integer division: 7 / 2 is 3. Write 7 / 2.0 when you want 3.5.
  • Comparing doubles with ==. Use a tolerance: std::abs(a - b) < 1e-9.
  • Storing money in double. Rounding errors accumulate into real accounting problems. Use integer cents.
  • Mixing signed and unsigned in comparisons. if (someInt < vec.size()) warns because size() is unsigned; the int gets converted and a negative value becomes huge.
  • Confusing 'A' and "A". Single quotes make a char, double quotes make a string literal.
  • Assuming int is 4 bytes everywhere. It is on mainstream desktops, but check with sizeof when portability matters.
  • Using float by default. double is the standard choice; float only pays off in very large arrays or on GPUs.

Best Practices

  1. Default to int and double. Reach for other types only when you have a concrete reason.
  2. Use braces to initialise: int n{value}; rejects narrowing conversions that = accepts silently.
  3. Prefer signed integers for arithmetic, even for values you expect to be positive; unsigned wraparound causes worse bugs than a negative number does.
  4. Use long long for ids and timestamps rather than discovering the limit in production.
  5. Query the compiler with sizeof and std::numeric_limits instead of memorising ranges.
  6. Mark values const the moment you know they will not change.

Practice Exercises

  1. Type report: Print the size in bytes and the min and max value for char, short, int, long long, float and double using sizeof and std::numeric_limits.
  2. Division trap: Write a program that reads two integers and prints their quotient both ways — as integer division and as true division — and explain the difference in a comment.
  3. Precision hunt: Add 0.1 to a double ten times in a loop and print the result with std::setprecision(20). Then do the same with a float. Report which one drifts further from 1.0 and why.