Reputation:
Why can you access enumerators outside the scope, while you can’t directly access a structure’s members directly? By scope, I mean the declaration scope - Please correct me if I am wrong.
To give an example: You can do this:
enum colors {red, blue, white};
int color = red;
but you cannot do this:
struct colors {red, blue, white};
int color = red;
Thanks!
Upvotes: 4
Views: 81
Reputation: 112356
Okay, well, as another comment said, it's because that's the way C++ works.
Back in the old days, we simulated something like this with something like
class Colors {
public:
static int RED = 0;
static int GREEN = 1;
static int YELLOW = 2;
}
Then enum was added so you didn't need to write Colors.RED
. It's essentially syntactic sugar.
Update
A scope is just the part of a program in which a name is visible. The rules can be simple, complicated or weird: C++ goes for complicated, JavaSccript goes for weird. You can see lengthy explanations here and here, but here's a basic notion.
In C++, which is a block-structured language that descended from Algol 60, a name is defined thoughout the block in which it's declared. One kind of block is the file. If a name is declared at the top of a file, it's defined everywhere in the file following the declaration.
Another kind of block is defined by a pair of braces {}
. Anything declared within braces is defined from the declaration up to the enclosing end brace. So
#include <stdlib> // copies a bunch of code into the file
int foo = 0; // declared here, visible to end.
int fn(){
int bar = 2 ;
if(bar == 2){
foo = bar;
cout << bar << nl; // gives '2'
cout << foo << nl; // still gives '2'
}
cout << foo << nl ; // gives '0'
cout << bar << nl ; // compile time error 'bar' not defined
}
Why? the inner foo
hides the outer foo
, so that's the one that gets printed inside the if
block. The bar
is defined at the top of the if
block, so it's no longer visible ("no longer in scope") after the brace ending the if
block
There are more rules, but I'd recommend reading about it in one of those links or a good C++ book.
Upvotes: 1
Reputation: 385114
There isn't a scope to be outside of. enum
doesn't introduce a new scope in the way that struct
does. Why? Well, why not. They are two entirely different things, so expecting one to work the same as the other is vacuous.
enum class
, however, does work that way; the feature is aptly called "scoped enums".
Upvotes: 0