Variables and Memory
Every variable lives somewhere in your computer's memory, and C++ is unusual among popular languages in letting you work with that memory directly.
Declaring variables
int xp = 100; // an integer variable holding the value 100
double price = 9.99; // a floating-point number
char grade = 'A'; // a single character
bool passed = true; // true or false
Every variable in C++ has a fixed type decided when it's declared, an int can never later hold a decimal or a piece of text.
Addresses, pointers, and references
Every variable lives at a specific address in memory, think of memory as a huge street of numbered houses, a variable's address is just its house number.
int xp = 100;
std::cout << &xp; // prints xp's address, e.g. 0x7ffc3a2b1c
int* ptr = &xp; // ptr is a pointer: it stores xp's address
std::cout << *ptr; // *ptr "dereferences" ptr: prints 100, the value at that address
int& ref = xp; // ref is a reference: another name for xp itself
ref = 200; // this actually changes xp too!
std::cout << xp; // prints 200
| Symbol | Meaning | Example |
|---|---|---|
&x | "address of x" | int* p = &x; |
*p | "the value at the address p points to" | std::cout << *p; |
T* | "a pointer to a T" | int* p; |
T& | "a reference to a T" | int& r = x; |
Pointers vs. references
- A pointer is a variable that stores an address, it can be reassigned to point somewhere else, or set to
nullptrto point at nothing at all. - A reference is an alias for an existing variable, it must be bound to something when it's created, and can never be changed to refer to something else afterward.
WARNING
A pointer that still holds the address of something that's already been destroyed is called a dangling pointer, dereferencing it is undefined behavior, one of the most common sources of bugs in C++. Always be sure what a pointer points at is still alive before you dereference it.