Values & References7 / 18
Up next

Null pointer as absence

#include <stdio.h>

int *find(int *a, size_t n, int target) {
    for (size_t i = 0; i < n; i++) {
        if (a[i] == target) {
            return &a[i];
        }
    }
    return nullptr;
}

int main(void) {
    int a[] = {3, 9, 2};
    int *hit = find(a, 3, 9);
    if (hit != nullptr) {
        printf("found %d\n", *hit);
    }
    return 0;
}
What you're solving

return nullptr for 'not found'