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>
usingnamespace std;
unordered_map<int, string> divisor; // Error is thrown here
divisor[10] = "Ten";
int main(){
return 0;
}
#include <iostream>
#include <string>
#include <unordered_map>
usingnamespace 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;
}
> 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
}
}