2

How the members of enums are accessed outside of enum since all members scope is limited to their block.

    #include<iostream>
    enum{MON,TUE,WED};

    using namespace std;
    int main(){
        cout << TUE;//How TUE is accessed since it has to be limited to enum's scope
        return 0;
}
  1. How the scope of enum members are outside of enums block since as in classes or structures the scope of it's member is limited to the block they defined.

  2. Since we are not creating object of enums then when the memory is allocated to enum members?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
mdadil2019
  • 807
  • 3
  • 12
  • 29
  • 4
    Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Aug 29 '17 at 11:53
  • 6
    That's not how an [unscoped enumeration](http://en.cppreference.com/w/cpp/language/enum#Unscoped_enumeration) works. It's how [**scoped** enumerations](http://en.cppreference.com/w/cpp/language/enum#Scoped_enumerations) works. – Some programmer dude Aug 29 '17 at 11:53

3 Answers3

3

Unscoped enums leak their names outside the enum {} braces in which they are defined and into the scope owning the enum which is a global scope, in your case. That's why you can't have a variable with the same name as one of the enums. Scoped enums don't leak their names outside the enum scope in which they are defined.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Ron
  • 14,674
  • 4
  • 34
  • 47
2

all members scope is limited to their block

No, that's not the case for an enum in C++: the scope is the namspace in which the enum is defined. That's the global one in your case.

The enum class of C++11 onwards addresses this by localising the enum values to that class.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

all members scope is limited to their block

No.

An enum in C++ has the same scope as the namespace it's defined in, which in your case is the global scope.

What you have is an unscoped enum. Maybe you are confused with scoped enums.


PS: The usage of anonymous enums.

gsamaras
  • 71,951
  • 46
  • 188
  • 305