Basic Syntax & Types¶
In this chapter, we will explore the building blocks of C++: variables, types, and how to manage data.
Comments¶
Comments are ignored by the compiler but are crucial for code readability.
Doxygen Style¶
For documentation generation, use /// or /** ... */.
Variables and Initialization¶
A variable is a named storage location in memory. In Modern C++, we strongly recommend using Uniform Initialization (brace initialization).
Why Uniform Initialization?¶
It prevents "narrowing conversions" (accidental data loss) and is consistent across all types.
Type Deduction (auto)¶
The auto keyword lets the compiler deduce the type from the initializer. This guarantees initialization and avoids type mismatches.
Fundamental Types¶
C++ provides a rich set of built-in types. On a 64-bit Raspberry Pi (ARM64), typical sizes are:
Integer Types¶
| Type | Size | Range (Approx) | Description |
|---|---|---|---|
int |
4 bytes | ±2 Billion | Standard integer |
short |
2 bytes | ±32,768 | Small integer |
long |
8 bytes | ±9 Quintillion | Large integer (64-bit) |
long long |
8 bytes | ±9 Quintillion | Guaranteed at least 64-bit |
Unsigned Types: Adding unsigned shifts the range to start at 0 (e.g., unsigned int is 0 to 4 Billion).
Floating-Point Types¶
| Type | Size | Precision | Description |
|---|---|---|---|
float |
4 bytes | ~7 digits | Single precision |
double |
8 bytes | ~15 digits | Double precision (Default) |
Other Types¶
bool: Represents truth values (trueorfalse). Size is usually 1 byte.char: A single character (ASCII). 1 byte.void: Represents the absence of a type (used for functions returning nothing).
Standard Library Types¶
Modern C++ encourages using standard containers instead of raw arrays or C-style strings.
std::string (Better than char*)¶
An object that manages memory for text automatically.
std::vector (Better than arrays)¶
A dynamic array that can grow and shrink.
Literals¶
Literals are fixed values written directly in code.
- Integer:
42,0xFF(Hex),0b1010(Binary). - Floating-point:
3.14,1.0f(Float). - String:
"Hello"(C-string),std::string("Hi")(std::string).
Constants¶
Immutability is key for robust software.
const vs constexpr¶
const: "I promise not to change this."constexpr: "This value is known at compile-time."
Mathematical Constants (C++20)¶
C++20 introduced standard mathematical constants in <numbers>.
Scope and Lifetimes¶
Variables have a scope (where they are visible) and a lifetime (when they exist in memory).
Local Scope (Block Scope)¶
Variables declared inside { ... } exist only within that block.
Global Scope¶
Variables declared outside any function. Avoid them if possible, as they make code hard to debug.
Type Conversion (Casting)¶
Sometimes you need to convert between types.
- Implicit: Automatic (e.g.,
inttodouble). - Explicit (
static_cast): The safe, modern way to cast.
Avoid C-style casts like (int)pi.