1. Goals
Distinguish a value snapshot from access to the original data.
Deduct stock only when the requested quantity is valid.
Find an array element without exceeding bounds or using an expired object.
2. Prerequisites
You have covered initialization, const, pointers, references, name scope,
lifetime, arrays, and parameter passing. This lesson combines them in a
small program with fixed data so you can predict and check the results.
3. Explanation
Three products have stock quantities 8, 0, and 5. Indices start at 0.
A valid sale requires amount > 0 and amount <= stock. Rejection leaves
stock unchanged; selling exactly the remaining quantity leaves 0.
takeStock(int& stock, int amount) receives an alias for the stock to update.
It checks before subtracting and returns true on success. For accepted
inputs, subtraction produces a value between 0 and the previous stock,
so it cannot overflow the integer type.
previewStock(int stock, int amount) receives a copy. It calls the same
takeStock function, but the reference now binds to its own local parameter.
The preview is returned by value; the array in main remains unchanged.
Similarly, snapshot stores the value at initialization and does not update
automatically when inventory changes.
findStock takes a pointer to the first array element, an element count,
and the requested index. It checks nullptr, count, and index before
calculating stocks + index. Valid indices belong to [0, count); failure
returns nullptr. It returns an element's address in the caller's array,
without creating a new element.
Functions accepting a pointer and count require a truthful pair from the
caller: when accessing elements, the pointer must identify the first element
of a live array containing at least count elements. The function cannot
discover the actual array size, so it cannot detect an exaggerated count.
nullptr or count <= 0 is handled without reading the array. Do not pass
an invalidated pointer to try this check.
view and the parameter of printInventory have type const int*: they
cannot modify elements, but still observe changes made by takeStock.
They neither copy nor own the array. stocks lives until the end of main,
longer than every pointer use in this example. Do not save these pointers
for use after the array's lifetime ends; a non-null pointer can still dangle.
4. Runnable example
Save as main.cpp, compile with C++17, and run; no input is needed.
#include <iostream>
bool takeStock(int& stock, int amount) {
if (amount <= 0 || amount > stock) {
return false;
}
stock -= amount;
return true;
}
int previewStock(int stock, int amount) {
takeStock(stock, amount);
return stock;
}
int* findStock(int* stocks, int count, int index) {
if (stocks == nullptr || count <= 0 || index < 0 || index >= count) {
return nullptr;
}
return stocks + index;
}
void printInventory(const int* stocks, int count) {
std::cout << "Stock:";
if (stocks != nullptr && count > 0) {
for (int index = 0; index < count; ++index) {
std::cout << ' ' << stocks[index];
}
}
std::cout << '\n';
}
int main() {
const int count = 3;
int stocks[count] = {8, 0, 5};
const int* view = stocks;
int snapshot = stocks[0];
std::cout << std::boolalpha;
printInventory(view, count);
std::cout << "Preview after selling 3: " << previewStock(stocks[0], 3) << '\n';
int* selected = findStock(stocks, count, 0);
if (selected != nullptr) {
std::cout << "Sell 3: " << takeStock(*selected, 3) << '\n';
printInventory(view, count);
std::cout << "Snapshot: " << snapshot << '\n';
std::cout << "Sell 0: " << takeStock(*selected, 0) << '\n';
std::cout << "Sell -2: " << takeStock(*selected, -2) << '\n';
std::cout << "Sell 6: " << takeStock(*selected, 6) << '\n';
std::cout << "Sell 5: " << takeStock(*selected, 5) << '\n';
}
int* last = findStock(stocks, count, count - 1);
if (last != nullptr) {
std::cout << "Sell last 2: " << takeStock(*last, 2) << '\n';
}
printInventory(view, count);
std::cout << "Missing -1: " << (findStock(stocks, count, -1) == nullptr) << '\n';
std::cout << "Missing 3: " << (findStock(stocks, count, count) == nullptr) << '\n';
std::cout << "Missing null: " << (findStock(nullptr, count, 0) == nullptr) << '\n';
return 0;
}Output:
Stock: 8 0 5
Preview after selling 3: 5
Sell 3: true
Stock: 5 0 5
Snapshot: 8
Sell 0: false
Sell -2: false
Sell 6: false
Sell 5: true
Sell last 2: true
Stock: 0 0 3
Missing -1: true
Missing 3: true
Missing null: true5. Common mistakes
Removing
&fromtakeStock: it only changes a copy, leaving inventory unchanged.Subtracting before checking: a rejected operation can still corrupt data.
Forming an out-of-bounds pointer before checking; validate the index first.
Using
*findStock(...)without first checking that the result is notnullptr.Returning the address of a local variable instead of the caller's element.
Assuming
const int*freezes data or a pointer extends the array's lifetime.
6. Practice
Implement all four functions before consulting the example. A rejected operation must return
falseand leave stock unchanged. Previewing must always leave the caller's data unchanged.Starting with stock
5for each independent case, quantities0,-1, and6must fail, leaving5; quantity5succeeds, leaving0. An empty stock of0cannot supply1item.For a three-element array, indices
0and2must return the corresponding addresses;-1,3,count = 0, and anullptrinput must returnnullptr.Change the first stock to
10: previewing a sale of3returns7, and the snapshot remains10. Following the sequence inmain, selling6now succeeds, selling5fails, and the final inventory is1 0 3.
7. Self-check
Why can
previewStockcall a function takingint&without changingmain's array? Answer: the reference binds to thestockparameter passed by value, which is a local copy, not a reference to the original element.Why does output through
viewchange from8to5despiteconst? Answer:constprevents modification throughview; it still observes the same element modified through a writable reference. It is not a snapshot.Why may
findStockreturn a pointer when returning a local variable's address is wrong? Answer: the element belongs to the caller's array and survives the call. An automatic local variable in the lookup function dies when it returns. The caller must still keep the array alive throughout use of the result.
Sample code
Source file
cpp98_foundation/12_stage2_practice/main.cpp
#include <iostream>
bool takeStock(int& stock, int amount) {
if (amount <= 0 || amount > stock) {
return false;
}
stock -= amount;
return true;
}
int previewStock(int stock, int amount) {
takeStock(stock, amount);
return stock;
}
int* findStock(int* stocks, int count, int index) {
if (stocks == nullptr || count <= 0 || index < 0 || index >= count) {
return nullptr;
}
return stocks + index;
}
void printInventory(const int* stocks, int count) {
std::cout << "Stock:";
if (stocks != nullptr && count > 0) {
for (int index = 0; index < count; ++index) {
std::cout << ' ' << stocks[index];
}
}
std::cout << '\n';
}
int main() {
const int count = 3;
int stocks[count] = {8, 0, 5};
const int* view = stocks;
int snapshot = stocks[0];
std::cout << std::boolalpha;
printInventory(view, count);
std::cout << "Preview after selling 3: " << previewStock(stocks[0], 3) << '\n';
int* selected = findStock(stocks, count, 0);
if (selected != nullptr) {
std::cout << "Sell 3: " << takeStock(*selected, 3) << '\n';
printInventory(view, count);
std::cout << "Snapshot: " << snapshot << '\n';
std::cout << "Sell 0: " << takeStock(*selected, 0) << '\n';
std::cout << "Sell -2: " << takeStock(*selected, -2) << '\n';
std::cout << "Sell 6: " << takeStock(*selected, 6) << '\n';
std::cout << "Sell 5: " << takeStock(*selected, 5) << '\n';
}
int* last = findStock(stocks, count, count - 1);
if (last != nullptr) {
std::cout << "Sell last 2: " << takeStock(*last, 2) << '\n';
}
printInventory(view, count);
std::cout << "Missing -1: " << (findStock(stocks, count, -1) == nullptr) << '\n';
std::cout << "Missing 3: " << (findStock(stocks, count, count) == nullptr) << '\n';
std::cout << "Missing null: " << (findStock(nullptr, count, 0) == nullptr) << '\n';
return 0;
}