Is the enum private to the function?
void doSomething()
{
enum cmds {
A, B, C
}
}
In an unscoped enum, the scope is the surrounding scope; in a scoped enum, the scope is the enum-list itself. In a scoped enum, the list may be empty, which in effect defines a new integral type. By using this keyword in the declaration, you specify the enum is scoped, and an identifier must be provided.
In C, there is simply no rule for scope for enums and struct. The place where you define your enum doesn't have any importance. In C++, define something inside another something (like an enum in a class) make this something belong to the another something.
The keyword 'enum' is used to declare new enumeration types in C and C++. Following is an example of enum declaration. // The name of enumeration is "flag" and the constant // are the values of the flag.
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
The enum cmds
type and the enumeration members A
, B
, and C
, are local to the function scope.
Note that while enumerations don't introduce a new scope for their member constants, they do get scoped within the containing scope, in this case the function body.
int doSomething(void)
{
enum cmds {
A, B, C // 0, 1, 2
};
return C; // returns 2
}
int anotherThing(void)
{
enum cmds {
C, D, E // 0, 1, 2
};
return C; // returns 0
}
Run the example code here on Coliru
Like almost any other declaration, an enum
type defined inside a block is local to that block.
In your case:
void doSomething()
{
enum cmds {
A, B, C
}
}
the block happens to be the outermost block of the function, but it doesn't have to be:
void doSomething(void) {
if (condition) {
enum cmds {A, B, C};
// The type and constants are visible here ...
}
// ... but not here.
}
(Goto labels are the only entity in C that actually has function scope.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With