C++ ยท Chapter 9 of 49

C++ Data Types

C++ has built-in primitive types including `int`, `double`, `float`, `char`, `bool`, and `std::string` for text (from the `<string>` header). Each type has a fixed size that determines the range of values it can hold.

Choosing the right type matters for both correctness and performance โ€” using `double` for money calculations or `int` for something that needs decimals will cause bugs.

Common types

`int` holds whole numbers (typically 32-bit), `double` and `float` hold decimals, `char` holds a single character, and `bool` holds true/false.

std::string

Unlike C-style char arrays, std::string manages its own memory and supports easy concatenation, comparison and length lookup via `.length()`.

Example 1 (cpp)
int a = 10;
double b = 3.14;
char c = 'A';
bool d = true;
std::cout << a << " " << b << " " << c << " " << d;
Output
10 3.14 A 1

bool prints as 1 (true) or 0 (false) by default.

Example 2 (cpp)
std::string s = "Hi";
std::cout << s.length();
Output
2

length() returns the number of characters in the string.

Key points

  • int, double, float, char, bool are primitive types.
  • std::string is the standard text type (needs #include <string>).
  • Each type has a fixed size/precision.
  • bool prints as 1 or 0 by default.
๐Ÿ’ก Note: Use `sizeof(type)` to check exactly how many bytes a type occupies on your platform.

๐Ÿ“ Quick Quiz

1. Which type holds decimal numbers with more precision?

2. Which header is required for std::string?

3. A bool variable set to true prints as: