The basket in the previous section owns its vector, but how long does the basket itself exist? Begin with ordinary local variables. A pair of block braces creates a scope: a local name is available from its declaration to the closing brace. For the automatic variables here, leaving the block also ends the object's lifetime. A variable in an outer block can stay alive while an inner variable comes and goes.
Use this to keep temporary calculations close to the work that needs them. A subtotal may be useful only while processing one order. You can copy its result into an outer variable before the block ends. The outer integer then stores its own value; it does not depend on the temporary variable remaining alive.
A copied value is safe here. A pointer or reference to the inner variable would be different: after the inner variable's lifetime ends, that pointer or reference must not be used to access it. Scope boundaries are therefore also boundaries you must consider when borrowing objects.
#include <iostream>
int main() {
int saved = 0;
{
int temporary = 6 * 3;
saved = temporary;
}
std::cout << saved << '\n';
}
The example prints 18 after the inner block has ended. The result survived because it was copied into saved, not because temporary stayed alive. In the task, subtotal is intentionally available only inside the block. Use its value while it exists, then inspect the outer collected value afterward. You need neither dynamic allocation nor a pointer for this calculation.
subtotal to collected. The outer value should remain available afterward and print Collected cents: 325.Edit main.cpp, then press Run to inspect the Console. Press Submit to check your work. Keep the supplied probes in place.