vectors scope

May 25, 2016 at 2:41pm
Hi guys I was expecting an out of scope error in my program but it worked fine with no errors I'm just wondering why this happens as I declared the items of myVector inside the main function yet I can still access them in a function outside the main function

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
  #include <iostream>
#include <vector>

using namespace std;

void printVector();

 vector<int> myVector;

int main()
{
    myVector.push_back(1);
    myVector.push_back(23);
    myVector.push_back(20);
    myVector.push_back(17);
    printVector();
}

void printVector(){

     for(unsigned int i = 0; i<myVector.size();i++){

           cout << myVector.at(i) << endl;
     }
}
May 25, 2016 at 2:50pm
1
2
3
4
5
vector<int> myVector;

int main()
{
...


Nope, you put it outside main so it exists everywhere.
May 25, 2016 at 2:56pm
yup but would that mean that all of myVectors elements can be accessed and declared anywhere also?
May 25, 2016 at 3:02pm
if it's not declared inside a function/class/struct... it's a global so can be seen everywhere. Where you set/get values does not change where it's visible from as that is the visibility.

some of this may help?

http://www.cplusplus.com/doc/tutorial/namespaces/
Last edited on May 25, 2016 at 3:05pm
Topic archived. No new replies allowed.