'does not name a type' error

using namespace std;

unordered_set<int> arr;
arr.insert(3);

int main(){ ... }

this above code gives error → error: ‘arr’ does not name a type
whereas the below code works fine

unordered_set<int> arr;

void func(){
       arr.insert(23);
       //....
}

int main(){ ... }

if we write inside the function, it works fine. What does that error mean?

1 Like

C++ is a language that is compiled and execution starts from main function i.e calls to any other function should be made from within the main function itself (its called calling hierarchy which always starts from the main function). In your first code snippet you called insert on arr outside the main function, that’s why it shows an error.

The area between the preprocessor directives (starting with #include<…>) and the main function can be used for declaring and assigning values to global variables, using namespaces, declaring custom type names for inbuilt names using “typedef” etc. We never call a function from outside the main function in C++.

1 Like

thank you dude i think your reply will help me..