Why map container does not work outside main

I am trying to use an unordered_map container outside main and it throws an error "This declaration class does not have a storage class or type specifier"
If I move this inside the main it does not complain. So my question is why does it throw an error when the container is outside main

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

unordered_map<int, string> divisor; // Error is thrown here
divisor[10] = "Ten";

int main(){
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

unordered_map<int, string> divisor; // Error is thrown here

divisor[10] = "Ten";  // No, the error is thrown here
                      // discarded-value expressions are not allowed at namespace scope

int main(){
return 0;
}


This is fine:
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <string>
#include <unordered_map>

std::unordered_map< int, std::string > divisor { { 10, "Ten" } } ; // initialisation

int main(){
    // ...
}
Oh, nice explanation, what is the reason it is not allowed at namespace scope? Does it have something to do with namespace storage constraints?
> Does it have something to do with namespace storage constraints?

No. The expression used as an initialiser of an object is not a discarded-value expression.
An expression statement consists of a discarded-value expression followed by a ;
The expression is evaluated and its value is discarded (not used, thrown away).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// i and j are variables at namespace scope; the objects have static storage duration
int i = 8 ; 
int j = i * i ; // the expression i * i is not a discarded-value expression, its value is used to initialise j

i = i + 78 ; // expression statement, i = i + 78 is the discarded-value expression
             //  i = i + 78 is evaluated and then the result of the evaluation is thrown away
             // this is not allowed at namespace scope (it is allowed at block scope)

void foo( int a )
{
    if( a > 6 ) 
    { 
        i = i + 78 ; // fine: expression statement at block scope
    }
}
Topic archived. No new replies allowed.