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()`.
int a = 10;
double b = 3.14;
char c = 'A';
bool d = true;
std::cout << a << " " << b << " " << c << " " << d;10 3.14 A 1bool prints as 1 (true) or 0 (false) by default.
std::string s = "Hi";
std::cout << s.length();2length() 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.
