Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do enum values behave like global variables?

Tags:

c++

enums

I have two enums, and if there is one value in one enum with the same name as a value in the other enum:

enum A {joe, bob, doc};
enum B {sunday, monday, doc};

The compiler (Visual Studio's) complains about redefinition of doc, which implies it treats it as a global variable. Is this so? It is not the behavior I would expect, and it forces me to manage names of all enum elements in my project.

Any insights would help.

like image 463
Itamar Katz Avatar asked Nov 24 '10 16:11

Itamar Katz


People also ask

Can We have variables and methods in enum in Java?

Can we have variables and methods in an enum in Java? Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc. You can define an enumeration using the keyword enum followed by the name of the enumeration as −

What are the values of constants and enum variables?

By default, the values // of the constants are as follows: // constant1 = 0, constant2 = 1, constant3 = 2 and // so on. enum flag {constant1, constant2, constant3, ....... }; Variables of type enum can also be defined. They can be defined in two ways:

What is the difference between ENUM and variable in C++?

We use enums for constants, i.e., when we want a variable to have only a specific set of values. For instance, for weekdays enum, there can be only seven values as there are only seven days in a week. However, a variable can store only one value at a time.

What is the use of enum in C++?

It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. 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.


1 Answers

It's not treated as a global variable. It's treated as a global identifier.

More precisely, it's treated as an identifier in whatever namespace the enum is declared in. In your case, that's the global namespace.

For an idea of what the difference is between a global identifier and a global variable, try taking the address of your enum. ;)

Usually when I define enums, I prepend the an abbreviated version of the name of the identifier. Like this:

enum InstrumentType { itStock, itEquityOption, itFutureOption };

This helps to avoid collisions.

like image 50
John Dibling Avatar answered Oct 01 '22 04:10

John Dibling