array of strings

Hi, i'm currently teaching myself c++. I was going to ask how to create an array of strings but i've managed to work it out. However, i do still have one question.

Here is how i've done it and it works fine:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include<string>

using namespace std;

int main() {

	string Names[4];
	Names[0] = "Will";
	Names[1] = "Tommy";
	Names[2] = "Alf";
	Names[3] = "John";

	for (int i = 0; i<4; i++) {
		cout << Names[i] << endl;
	}

}


However i noticed that creating the array outside of main() does not work, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include<string>

using namespace std;

string Names[4];
Names[0] = "Will";
Names[1] = "Tommy";
Names[2] = "Alf";
Names[3] = "John";

int main() {

	for (int i = 0; i<4; i++) {
		cout << Names[i] << endl;
	}

}


Why does this not work? it seem completely illogical to me!
The same reason you can't have, say, i += 2; in the global scope. It needs to be in a function. The array definition alone could be global, however.
After reading your answer, i've realised when defining any variables i've always done either int i = 2; or just int i; and then set a value later within a function. Never have i used
1
2
int i;
i = 2;

so it makes sense now why the array thing would not work. It seems like a silly question now!

Thanks for your answer!
Topic archived. No new replies allowed.