Questions about enums

I have a few questions about enums, here they are:

1. Are enum elements constant? so if i do

1
2
3
4
5
enum wind
{
  east = 10,
  west = 3
};


would these be constant or could they be changed?

2. What would i use enums for why are they useful? how would i use them in, lets say programming a game?
ch1156..
your level indicates you probably know more anyway, but here are is my comment-feel free to ignore if you feel it is something you already know.

enum replaces a number with a name.

1
2
3
4
5
enum wind
{
  east = 10,
  west = 3
};


Same as
1
2
const int east = 10;
const int west =3;


I believe by using enum you don't have to specify a number that it is equal to and yet you are guaranteeing that they are all different.

Refer to this link for a more detailed info from the more experience coders
http://www.cplusplus.com/forum/beginner/44859/
Last edited on
Also see the Enumerations (enum) section of the cplusplus.com turorial on this page:

Other Data Types
http://cplusplus.com/doc/tutorial/other_data_types

1) Enum values are const, so you cannot change them

2) They are useful when you want to identify a restricted set of identifiers. It stops you using the wrong id in the wrong place. e.g. the suite of a card. If you use ints, you could accidentally use a value which doesn't map to a suite. But if you use enum Suite { spades, hearts, diamonds, clubs }; then the compiler will pick up if you try to use anything other than these values (assuming you use the enum type for variables and function parameters).

Enums can also be used as normal consts. This was particularly useful in class definitions back in the "olden days", before you could define a static const integer member of a class inline. And people do still use the "hack".

The Enum Hack
http://cpptrivia.blogspot.co.uk/2010/12/enum-hack.html

Note that enum values can be the same. If you don't supply a specific value then an enum value will be one more than the previous one (starting from zero). e.g. from above, spades = 0, hearts = 1, diamonds = 2, clubs = 3.

But in the case of enum Boolean {True = 1, False = 0, Vrai, Faux = 0, Cierto, Falso = 0}; then True, Vrai, and Cierto all have the same value and False, Faux, and Falso similarly.

(You shouldn't really need to know what the actual values are. That should be the IDE/compiler's problem.)

Andy
Last edited on
One other comment, though you can use enum for simple values like 1, 2, 3, 4, they might also be useful for obscure numbers, such as the numeric code corresponding to a particular key, or some other value which may otherwise be difficult to remember - though an ordinary const may also serve that purpose.
Topic archived. No new replies allowed.