Not every selection has a target. A pointer can represent this deliberately with nullptr, a C++ value meaning “no object.” This is different from pointing to an integer whose value happens to be zero: that integer still exists.
Never dereference nullptr. First compare the pointer with it, then access the object only in the branch where the pointer is known to identify a live target. A null check does not prove that an arbitrary non-null pointer is valid; the program must also keep its target alive.
#include <iostream>
int readOrZero(const int* value) {
if (value == nullptr) {
return 0;
}
return *value;
}
int main() {
int visitors = 11;
std::cout << readOrZero(&visitors) << '\n';
std::cout << readOrZero(nullptr) << '\n';
}
The output is 11 and 0. The early return ends the missing-target call before dereferencing. For the other call, visitors remains alive throughout the function.
const int* means a pointer through which the integer can only be read. The function may inspect *value but may not change it. The pointer itself is passed by value, so the function receives a copy of the address, not a copy of the pointed-to integer. A writable pointer would instead use int*.
The starter has two temporary return -99; statements. They are in different paths: the first handles nullptr, and the second handles a supplied live target. Replace the return inside the null branch with the missing-value marker -1. Only the return after that branch should read through the pointer. Because the null branch returns immediately, a missing target never reaches that later dereference.
-1 in the null-pointer branch. Expect Missing: -1.units. Expect Present: 8.Edit main.cpp, then select Run to inspect the Console. Select Submit to check your completed tasks.