Legacy C++ › 1. Getting Started
Variables, Types and Literals
Fundamental types, sizes, signed/unsigned, literals and conversions.
beginner #types#literals#conversions#limits
Explanation
Fundamental types:
| Type | Typical size | Notes |
|---|---|---|
bool |
1 byte | true / false |
char |
1 byte | character or small integer |
short, int, long |
2, 4, 4 or 8 bytes | sizes are implementation-defined; only minimums are guaranteed |
float, double, long double |
4, 8, 8+ bytes | IEEE 754 on almost all platforms |
Integer types can be signed (default) or unsigned. sizeof(T) gives the size in bytes, and <climits> / <limits> give the ranges.
Literals: 42 (int), 42L (long), 42U (unsigned), 3.14 (double), 3.14f (float), 'a' (char), "text" (array of const char), 0x1F (hex), 017 (octal; a leading zero!).
Example
#include <iostream>
#include <climits>
#include <limits>
int main() {
std::cout << "int: " << sizeof(int) << " bytes, max " << INT_MAX << "\n";
std::cout << "long: " << sizeof(long) << " bytes\n";
std::cout << "double: " << sizeof(double) << " bytes, eps "
<< std::numeric_limits<double>::epsilon() << "\n";
int i = 7;
double d = i / 2; // integer division first: 3
double e = i / 2.0; // 3.5
std::cout << d << " " << e << "\n";
unsigned u = 0;
--u; // wraps around to UINT_MAX (well-defined)
std::cout << u << "\n";
int big = INT_MAX;
// ++big; // signed overflow: undefined behavior
return 0;
}
Common pitfalls
- Integer division truncates:
7 / 2 == 3. Make one operand floating-point. - Signed overflow is undefined behavior; unsigned overflow wraps modulo 2^n.
- Mixing signed and unsigned in comparisons converts the signed value:
-1 < 1uis false. intis not always 32 bits andcharmay be signed or unsigned. Do not assume.- A leading
0makes an octal literal:010 == 8.
Legacy vs modern
C++11 adds long long, fixed-width types in <cstdint> (int32_t, uint64_t), auto, and brace initialization that rejects narrowing. C++14 adds binary literals (0b1010).
Exercises
1. What does std::cout << (5 / 2.0f) print?
2.5: the int is converted to float.
2. Why is for (unsigned i = 10; i >= 0; --i) an infinite loop?
An unsigned value is never negative, so i >= 0 is always true; decrementing from 0 wraps to the maximum value.