Values & References8 / 16
Up next

Pointers can be null

#include <print>
#include <vector>

// return a pointer so "not found" can be null
int* find_first_even(std::vector<int>& v) {
    for (int& x : v) {
        if (x % 2 == 0) {
            return &x;
        }
    }
    return nullptr;
}

int main() {
    std::vector<int> v{1, 3, 6, 7};
    if (int* p = find_first_even(v)) {
        std::println("found {}", *p);
    } else {
        std::println("none");
    }
}
What you're solving

check before dereferencing