Lesson 28 +10 XP

Fundamental Data Types

Fundamental Data Types

Before a program can store anything, it has to know what kind of thing it is storing. That's the job of a data type.

What is a type?

A type tells the compiler two things: how much memory the value uses, and how that memory should be interpreted. 5 could be a count, a temperature, or a code - the type decides.

The fundamental types

C++ gives us a small set of built-in (fundamental) types:

bool     // true or false
char     // a single character
int      // a whole number
float    // a decimal number (less precision)
double   // a decimal number (more precision)
void     // "no type"  -  for functions that return nothing

The standard size table

Sizes can vary slightly by machine, but on most modern desktop systems:

TypeTypical sizeTypical range
bool1 bytetrue or false
char1 byte-128 to 127 (or 0 to 255)
int4 bytesabout -2.1 billion to 2.1 billion
float4 bytesabout 7 decimal digits of precision
double8 bytesabout 15 decimal digits of precision
voidn/ano value

Why "typical"?

The standard only guarantees minimum sizes, not exact ones. That's why sizeof (we'll meet it soon) matters: the only honest way to know a type's size on your machine is to ask.

Picking the right type

  • Store a yes/no? Use bool.
  • Store one character? Use char.
  • Count things? Use int (or a wider integer for big numbers).
  • Measure with decimals? Use double.
  • Functions that return nothing? Use void.

TL;DR

  • A type says how much memory a value uses and how to interpret it.
  • Fundamentals: bool, char, int, float, double, void.
  • Typical sizes: int 4 bytes, double 8 bytes, char 1 byte.
  • Sizes vary by machine; only the minimums are guaranteed.
  • Pick the type that matches what you're storing.