A girl and a robot thinking together

Think it through together · A little story

Two functions both name a temporary score temp. Will they fight over the same score sheet?

Lay out the process

Follow the numbered steps, then explain them in your own words
  1. Enter function ACreate A’s temporary value
  2. Enter function BCreate B’s temporary value
  3. B endsB’s ordinary local value reaches the end of its lifetime
  4. A continuesUse A’s value

Local variables are used within particular scopes. Different functions can have local variables with the same name, but they are not the same object.

Imagine each function call carrying its own work sheet.

01What is a local variable?

void test() {
    int score = 95;
}

score is a local variable in the function body. Its name can be used only in the relevant scope.

02Can you access it after leaving the function?

void test() {
    int score = 95;
}

int main() {
    std::cout << score; // Error
}

The name score is not in main’s scope.

03Are scope and lifetime the same thing?

No.

Scope

The parts of the source code where a name can be used.

Lifetime

The period from when an object begins to exist until it stops existing.

They are often related, but they are not the same concept.

04Do all local variables live on the “stack”?

In many real implementations, ordinary local objects in a function may be placed in a stack frame on the runtime call stack.

But the C++ language standard does not require this for every local variable.

05Can a block have its own local variables?

int x = 1;

if (x > 0) {
    int y = 2;
    std::cout << y;
}

// y cannot be used here

Braces create a block scope. y is visible only inside that block.

06Can two functions have variables with the same name?

void a() {
    int x = 1;
}

void b() {
    int x = 2;
}

Yes. They belong to different scopes and are two distinct objects.

07Why limit the scope of local variables?

Fewer conflicts

Different functions can safely use their own names.

Clearer structure

Data appears only where it is really needed.

Easier management

Objects do not need to exist forever.

What you have learned

  • A local variable can be accessed by name only within its corresponding scope.
  • Scope and lifetime are not the same concept.
  • When an automatic-storage local object leaves its scope, its lifetime usually ends.
  • “Local variables are always on the stack” is not a strict C++ rule.
  • Different functions can have independent local variables with the same name.

Next: What happens when one function calls another?

Your turn to try

A’s temp is 3. B changes its own temp to 9. Does A’s temp also become 9?

Have you thought it through? Open for an explanation

No. Having the same name does not connect the variables. If data is shared through a reference or another mechanism, consider that actual relationship separately.