Recognizing Global Variables in Different Functions

Hey all,

I am creating a text based RPG, nothing special, I am still a beginner, and I was wondering how I would be able to make global variables recognizable by multiple functions after being changed in the first function. For example...

Code is in C++...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;

//Functions
int character();
int storyline();

//Global Variable
char name;

//function sequence
int main(){
character();
storyline();
return 0;
}

//Character creation function
int character(){
cout << "Please enter your name: ";
char name[20];
cin >> name;
cout << "Your name is: " << name << "\n" << endl;
return 0;
}

//Storyline function
int storyline(){
cout << name << " begins his journey to..." << endl;
return 0;
}

/*The problem I am having is that after the user inputs their name into the
 character selection function, it no longer recognizes it in the storyline
 function (Notice how when you run the program there is a blank where your 
 name should be). I am looking for a way to fix it and if anyone thinks they 
 can help me it it would be much appreciated!*/


Thanks,
CloudIsland
In your character function, you're not storing it the global variable called name. You're storing it in a local variable that you've also called name, which you've declared on line 21. This local variable called name hides the global variable called name.

In any case, global variables are a very bad habit, that can cause all kinds of problems in your code. I strongly recommend not using them.
Topic archived. No new replies allowed.