blog.dopana

Back

Fifth post in the basic C++ series. Variables live in memory at an address. Pointers and references are two ways to talk about a variable indirectly — both essential in C++.

Address of a variable#

Every variable sits at a memory address. Take it with &:

int a = 42;
std::cout << &a << '\n';   // something like 0x7ffee2b3d5ac
cpp

Pointers#

A pointer stores an address. It has a type that says what it points to:

int a = 42;
int* p = &a;    // p points to a
cpp

Dereference with * to read or write through the pointer:

std::cout << *p << '\n';   // 42
*p = 100;                  // changes a
std::cout << a << '\n';    // 100
cpp

The null pointer#

A pointer can hold no address. Use the keyword nullptr and always check before dereferencing:

int* p = nullptr;

if (p != nullptr) {
    std::cout << *p << '\n';
}
cpp

Dereferencing nullptr is a crash — a null pointer dereference.

References#

A reference is an alias for an existing variable. It is bound once and can never be re-bound:

int a = 42;
int& r = a;     // r is another name for a
r = 100;        // changes a
std::cout << a << '\n';   // 100
cpp

References cannot be null and cannot point to a different variable later.

Passing to functions#

Pass by reference to modify the caller’s variable without copying:

void increment(int& x) {
    ++x;
}

int main() {
    int a = 5;
    increment(a);
    std::cout << a << '\n';  // 6
}
cpp

Use const int& when you want to avoid copying but not modify:

void describe(const std::string& s) {
    std::cout << s.size() << '\n';
}
cpp

Pointers vs references#

PointerReference
Can be nullYes (nullptr)No
Can change targetYesNo
Must dereferenceYes (*)Implicitly
Reassignmentp = &otherNot allowed

In modern C++, prefer references for function parameters. Use pointers when “no value” is a valid state or when rebinding is needed.

Conclusion#

Pointers and references both reach variables indirectly. Prefer references for safety, use pointers when null or rebinding matters. Next in this series: classes and objects.

References#