That works. It remembers your name in the Adventure function. |
No it doesn't. Or at least if it does, it's a fluke that it does. You are relying on undefined behavior here which is very very bad.
This is a scope issue. A variable exists only inside its current scope -- scope is determined usually by the bounding {curly braces}. Example:
1 2 3 4 5 6 7 8 9
|
int main()
{
{ // some braces to create a scope
int foo = 5;
cout << foo; // prints '5' as you'd expect
} // <- foo's scope ends here
cout << foo; // COMPILER ERROR - 'foo' doesn't exist any more
}
|
As this example shows, 'foo' does not exist outside its scope. As soon as its scope ends, the variable is destroyed and its contents lost.
You have the same issue in your first code snippit. Your 'name' variable on line 12 has a scope that limits it to the 'Introduction' function.
That variable does not exist outside of that function.
The 'name' you create on line 24 is
not the same variable. It doesn't matter that it is also called 'name'... it's an entirely different block of memory that has its own contents.
The key problem here is that 'name' is local to 'Introduction'... which means as soon as 'Introduction' exits, you lose the name. You need to give 'name' a broader scope.
One way to do this is to create 'name' local to 'main', and pass to to whatever sub functions that need it as a parameter:
1 2 3 4 5 6 7 8 9 10 11 12
|
int main()
{
char name[10];
Introduction( name );
}
void Introduction( char* username )
{
// do stuff with 'username' here
// since main passed in 'name' as this parameter, reading or modifying
// Introduction's 'username' is the same as reading/modifying main's 'name'
}
|
In this case, 'name' has a scope local to main, which means it will stick around as long as main() is still running (which will be pretty much the entire lifetime of the program). Since we want to use 'name' outside of main, we can pass it as a parameter to whatever other functions that need it.