Thuta Learning
C++
BasicProgrammingBeginner

Data Types

C++Lesson 630 min

What you'll walk away with

  • Choose between int, double, char, bool and std::string by the value each one holds
  • Use sizeof and std::numeric_limits to find a type's size in bytes and its largest value
  • Explain when to use fixed-width types such as std::int32_t, std::int64_t and std::uint8_t
  • Explain why 7 / 2 is 3 and why 0.1 + 0.2 is not equal to 0.3
  • Convert explicitly with static_cast and spot overflow before it happens

Explain it simply

Explain it simply

A data type tells the compiler what kind of value a variable holds and how much memory it needs. Think of containers: a pill box, a water bottle and a shipping crate are each shaped for what goes inside, and putting the wrong thing in one either fails or makes a mess. C++ has built-in types for whole numbers, decimal numbers, single characters and true/false values, and the standard library adds std::string for text.

The type you pick also decides what operators mean. 7 / 2 is 3 when both numbers are whole numbers, but 3.5 when one of them has a decimal point. Choosing a type is therefore a decision about range, precision and behavior, not just about storage.

Problem → Why → Solution

The problem: three numbers that go wrong without an error

A shop script reports a price, an average rating and a total page-view count. Three plain-looking lines go wrong at once: int price = 19.99; stores 19, int average = 7 / 2; stores 3, and int views = 3'000'000'000; stores a negative number. Compiled with g++ -Wall -Wextra, none of the lines produces a warning, and the program runs to the end and prints 19 3 -1294967296.

shop_report.cpp
#include <iostream>

int main() {
    int price = 19.99;            // 19: the .99 is dropped
    int average = 7 / 2;          // 3: whole-number division
    int views = 3'000'000'000;    // does not fit in a 32-bit int
    std::cout << price << ' ' << average << ' ' << views << '\n';
}

Why does this happen?

Every one of these results is a legal consequence of the type rules. An int is typically 4 bytes, so it holds values up to 2,147,483,647 only, and a larger value wraps around modulo 2^32 to the part that fits. Converting to a smaller or less precise type keeps what fits and drops the rest. Dividing two whole numbers is whole-number division. The compiler assumes you meant it. Brace initialization catches the first and third of these: int price{19.99}; does not compile.

Core concept: a type fixes the byte count and the meaning

A type tells the compiler two things: how many bytes a value occupies, and how to read the bits in them. The same eight bits can mean the number 65 or the letter A, depending on whether the variable is an int or a char. The sizeof operator reports the byte count of a type or a variable, and std::numeric_limits<T> from <limits> reports the largest and smallest values of that type.

The integer family is int, short, long and long long, plus unsigned versions. The standard guarantees only minimum sizes, so they vary: int is 4 bytes on mainstream platforms, but long is 4 bytes on Windows and 8 on 64-bit Linux and macOS. When the exact size matters, use the fixed-width types from <cstdint>, such as std::int32_t, std::int64_t and std::uint8_t; the number of bits is in the name.

Every integer type has a range: a 4-byte int stops at 2,147,483,647. Unsigned types wrap around by definition: subtracting 1 from 0 in a 32-bit unsigned int gives 4,294,967,295. Signed overflow is different. It is undefined behavior, so do not count on it wrapping.

double (8 bytes, about 15 decimal digits) and float (4 bytes, about 6) store numbers with a fractional part in binary. Most decimal fractions such as 0.1 have no exact binary form, so results are a tiny bit off: 0.1 + 0.2 is 0.30000000000000004. Make double your default, and compare with a tolerance instead of ==.

char holds one character as a small integer code, and bool holds true or false. std::string is a library type rather than a built-in one, and holds text of any length. Operators follow the types of their operands, so 7 / 2 is 3 because both are int, while 7 / 2.0 is 3.5.

Mental model: a type is three promises
  1. Type fixes how many bytes are used
  2. Bits are read according to the type
  3. Operators follow the operand types
  4. Past the range, errors stay silent

A number can look right while its type is wrong and the compiler will not complain, so ask yourself how big the value can get.

General pattern: choosing and measuring types

cpp
Type name{value};                  // int, double, char, bool, std::string
std::int32_t exact{value};         // fixed width: int8/16/32/64_t, uint8/16/32/64_t
sizeof(Type)                       // bytes used by a type (or by a variable)
std::numeric_limits<Type>::max()   // largest value; needs <limits>
static_cast<Target>(value)         // explicit, visible conversion
7 / 2    ->  3                     // int / int: whole-number division
7 / 2.0  ->  3.5                   // one double: decimal division

The first two lines declare variables, sizeof and numeric_limits ask a type for its size and range, and static_cast makes a conversion visible in the code. The last two lines show how operand types change the result.

Example: a course's facts, each with its own type

This program stores six values in variables of different types and prints the student count, the average, the section, whether the course is passed and the download count. Each line also shows how many bytes the type uses, via sizeof. downloads is 3 billion and does not fit in an int, which is why it is a std::int64_t. Predict the output first, especially how the bool is printed.

course_facts.cpp
#include <cstdint>
#include <format>
#include <iostream>
#include <string>

int main() {
    int students{35};
    double average{82.75};
    char section{'B'};
    bool passed{true};
    std::string course{"C++ Foundation"};
    std::int64_t downloads{3'000'000'000};  // does not fit in a 32-bit int

    std::cout << course << '\n';
    std::cout << std::format("Students: {} ({} bytes)\n", students, sizeof(students));
    std::cout << std::format("Average: {} ({} bytes)\n", average, sizeof(average));
    std::cout << std::format("Section: {} ({} byte)\n", section, sizeof(section));
    std::cout << std::format("Passed: {} ({} byte)\n", passed, sizeof(passed));
    std::cout << std::format("Downloads: {} ({} bytes)\n", downloads, sizeof(downloads));
    return 0;
}

Code breakdown

  1. Line 7int students{35};

    A whole number. int is the everyday default, a good fit for counts, indexes and ages.

  2. Line 8double average{82.75};

    A double for a measurement with a fractional part. A value like 82.75 happens to be exact in binary, but one like 0.1 is not.

  3. Line 9char section{'B'};

    Single quotes mean one character, stored in 1 byte. Double quotes would make a string literal instead of a char.

  4. Line 10bool passed{true};

    A bool holds only true or false. std::format spells a bool as the word true, while plain std::cout without boolalpha would print 1.

  5. Line 12std::int64_t downloads{3'000'000'000};

    int64_t is exactly 64 bits and holds 3 billion comfortably. The ' separators only make the long number readable; they do not change the value.

  6. Line 15sizeof(students)

    Given a variable, sizeof returns the size of its type in bytes. On this platform an int is 4, a double 8, and a char and a bool 1.

You should see
C++ Foundation
Students: 35 (4 bytes)
Average: 82.75 (8 bytes)
Section: B (1 byte)
Passed: true (1 byte)
Downloads: 3000000000 (8 bytes)

The basic types at a glance

TypeTypical sizeUse it for
int4 bytesWhole numbers: counts, indexes, ages
std::int64_texactly 8 bytesLarge counts, timestamps, file sizes
std::uint8_texactly 1 byteRaw bytes and small values from 0 to 255
double8 bytesMeasurements, averages, fractional calculations
float4 bytesGraphics and big arrays where memory matters
char1 byteA single character
bool1 byteYes/no decisions
std::stringvaries (library type)Text of any length

You can measure these on your own machine. The program below prints the largest values of int, int64_t and uint8_t, and how many decimal digits float and double are guaranteed to keep. Notice the + in front of the uint8_t value; the Common mistakes section explains why it is there.

limits.cpp
#include <cstdint>
#include <iostream>
#include <limits>

int main() {
    std::cout << "int max:       " << std::numeric_limits<int>::max() << '\n';
    std::cout << "int64 max:     " << std::numeric_limits<std::int64_t>::max() << '\n';
    std::cout << "uint8 max:     " << +std::numeric_limits<std::uint8_t>::max() << '\n';
    std::cout << "double digits: " << std::numeric_limits<double>::digits10 << '\n';
    std::cout << "float digits:  " << std::numeric_limits<float>::digits10 << '\n';
    return 0;
}
output
int max:       2147483647
int64 max:     9223372036854775807
uint8 max:     255
double digits: 15
float digits:  6

Conversions: widening, truncating and static_cast

C++ converts between types automatically, which is called an implicit conversion. Widening conversions that keep the value, such as char to int or int to double, are safe. Going from double to int cuts the fraction toward zero, so -2.7 becomes -2 and 2.99 becomes 2; there is no rounding. When you want the conversion to be visibly deliberate, use static_cast<Target>(value).

In the program below, wrong divides int by int first and only then widens to a double, so it gets 84. right casts first and divides second, so it gets 84.67. The = on the wrong line is deliberate: with {} GCC reports the int-variable-to-double step as narrowing, so the demonstration needs copy initialization.

conversions.cpp
#include <format>
#include <iostream>

int main() {
    int total{254};
    int count{3};

    double wrong = total / count;                      // int division first, then widened
    double right{static_cast<double>(total) / count};  // convert first, then divide
    std::cout << std::format("{} {:.2f}\n", wrong, right);

    double temperature{-2.7};
    int whole{static_cast<int>(temperature)};          // truncates toward zero
    std::cout << std::format("{} {}\n", whole, static_cast<int>(2.99));

    char letter{'A'};
    int code{letter};                                  // char widens to int safely
    char next{static_cast<char>(letter + 1)};          // letter + 1 is an int again
    std::cout << std::format("{} {} {}\n", letter, code, next);
    return 0;
}
output
84 84.67
-2 2
A 65 B

Mixing signed and unsigned

With int balance{-1}; unsigned int limit{1};, the test balance < limit is false, because -1 becomes 4294967295 when converted to unsigned. GCC warns with -Wall: "comparison of integer expressions of different signedness: 'int' and 'unsigned int' [-Wsign-compare]". Do not ignore that warning.

In real projects

How real projects choose types

Money is the classic example. Programs that handle prices store them as whole numbers of the smallest unit, cents for dollars or whole kyat when no fractions are needed, in a std::int64_t, because a double cannot hold a value like 0.1 exactly. Adding 0.1 ten times gives 0.9999999999999999, not 1. The integer is formatted only for display, so 1999 cents is shown as 19.99.

Width matters at the boundaries between systems. Network protocols and file formats define each field's size exactly, so code that reads them uses std::uint8_t, std::uint16_t and std::uint32_t. Unix timestamps stored in a signed 32-bit integer overflow in January 2038, which is why modern systems use 64-bit time values. Game and graphics code uses float for coordinates and colours, because a GPU handles millions of them and halving the memory matters, while scientific code defaults to double for the extra precision.

Common mistakes

Common mistakes with data types

1. Dividing two ints and expecting decimals

int average = total / count; throws the fraction away, and double result = total / count; does not rescue it, because the right side is evaluated as int / int before it is widened. With total 254 and count 3 you get 84, not 84.67. Convert one operand first: static_cast<double>(total) / count.

2. Comparing doubles with == or storing money in a double

double sum{0.1 + 0.2}; makes (sum == 0.3) false, because sum is 0.30000000000000004. Compare with a tolerance such as std::abs(sum - 0.3) < 1e-9 (this needs <cmath>). For money, store the smallest unit, such as cents, in an integer.

3. Letting a value outgrow its type

int views = 3'000'000'000; compiles without a single warning under -Wall -Wextra and stores -1294967296, because the value wraps around to fit 32 bits. A sum that overflows an int is worse: it is undefined behavior, so one build may show a wrapped number and another behave differently once optimization changes. Pick a wider type such as std::int64_t before values can get large.

4. Printing an 8-bit integer and getting a letter

std::cout << age with std::uint8_t age{65}; prints A, not 65, because uint8_t is a type from the char family. Printing +age or static_cast<int>(age) gives 65, and std::format("{}", age) also writes 65.

Best practices

Best practices

  • Default to int for whole numbers and double for fractions, and have a reason when you pick anything else.
  • Use fixed-width types such as std::int64_t and std::uint8_t when the exact size or a large range matters.
  • Use static_cast for every conversion so that truncation and narrowing are visible in the code.
  • Do not mix unsigned counts with negative arithmetic, and treat the sign-compare warning from -Wall -Wextra as a bug.

Mini challenge

Mini challenge: a marks report

Compute a total and an average from three marks, once with int arithmetic and once with decimals, and print a report that shows the difference. Then store a download count in a type that can hold it.

  • Store the marks 78, 91 and 85 in three int variables with braces and compute total as an int
  • Store total / 3 once in an int and once in a double, using static_cast<double>
  • Store 3'000'000'000 in a std::int64_t and print its size in bytes with sizeof
  • Use std::format to print the average with two decimal places
marks_report.cpp
#include <cstdint>
#include <format>
#include <iostream>

int main() {
    // TODO: three int marks (78, 91, 85) and their total

    // TODO: wholeAverage = total / 3 in an int
    // TODO: realAverage = total / 3 in a double; cast one operand first

    // TODO: a std::int64_t downloads variable holding 3'000'000'000

    // TODO: print Total, Integer average, Real average ({:.2f}) and
    //       Downloads with sizeof(downloads)
    return 0;
}

Expected: The output should be: Total: 254 Integer average: 84 Real average: 84.67 Downloads: 3000000000 (8 bytes)

Show hint

Casting total with static_cast<double>(total) makes / 3 a decimal division. When initializing a double with braces, the expression on the right must already be a double. std::format("{:.2f}", value) prints two decimal places.

Show solution
marks_report.cpp
#include <cstdint>
#include <format>
#include <iostream>

int main() {
    int mark1{78};
    int mark2{91};
    int mark3{85};
    int total{mark1 + mark2 + mark3};

    int wholeAverage{total / 3};                      // int / int: fraction dropped
    double realAverage{static_cast<double>(total) / 3};
    std::int64_t downloads{3'000'000'000};

    std::cout << std::format("Total: {}\n", total);
    std::cout << std::format("Integer average: {}\n", wholeAverage);
    std::cout << std::format("Real average: {:.2f}\n", realAverage);
    std::cout << std::format("Downloads: {} ({} bytes)\n", downloads, sizeof(downloads));
    return 0;
}

Quick quiz 1 / 3

What does int a{7}; int b{2}; std::cout << a / b << ' ' << static_cast<double>(a) / b; print?

Quick quiz 2 / 3

Which declaration can hold 5,000,000,000 and compiles with brace initialization?

Quick quiz 3 / 3

What is the output of unsigned int items{0}; items = items - 1; std::cout << items; (32-bit unsigned int)?

What to remember

  • A type fixes the byte count, how bits are read and how operators behave; measure it with sizeof and std::numeric_limits.
  • Pick int, double, char, bool and std::string by the value, and a fixed-width type like std::int64_t when the exact size matters.
  • int / int drops the fraction, and doubles cannot hold values like 0.1 exactly, so do not compare them with ==.
  • Unsigned types wrap, signed overflow is undefined behavior, and every conversion deserves a static_cast.

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Data Types | Thuta Learning