Local Variables Being Passed ( C++)

Viewed 132

I have encountered a problem in my learning of C++, where a local variable in a function is being passed to the local variable with the same name in another function, both of these functions run in main().

When this is run,

#include <iostream>
using namespace std;

void next();
void again();

int main()
{
    int a = 2;
    cout << a << endl;
    next();
    again();
    return 0;
}

void next()
{
    int a = 5;
    cout << a << endl;
}

void again()
{
    int a;
    cout << a << endl;
}

it outputs:

2
5
5

I expected that again() would say null or 0 since 'a' is declared again there, and yet it seems to use the value that 'a' was assigned in next().

Why does next() pass the value of local variable 'a' to again() if 'a' is declared another time in again()?

3 Answers
Related