Enumerated type include?

closed account (zN0pX9L8)
What do I need to include (like #include <iostream.h>) to make an enumerated type work?

I'm trying to declare my enum, but it doesn't work :

enum alphabet = {A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z};
Last edited on
You don't.

I surely would like to know what teacher is having you all create enumerations named A, B, C, etc. That's a horrifically bad idea, plus it is not in line with the purpose of enumerations.

If all you need is an index into a sequence, just use a number.

However, if you have a list of constant values whose actual value doesn't matter and/or where the name is more important, then you use an enum.

For example, a good enum:
1
2
3
4
5
6
7
enum EOL_t {
  eolDefault,
  eolPreserve,
  eolUnix,
  eolWindows,
  eolMacintosh
  };

Just by looking at it you can guess that it has something to do with the way end-of-line sequences are managed by one or more file-handling functions. The actual value of each enumeration is not the least bit important. What is important is its meaning. I could shuffle the names around and the program would still compile and operate just fine.

However, in the case of an alphabet, it already has a predefined, sequential (or ordered) meaning. B follows A. C follows B. We can talk about the third letter of the alphabet and people know that you mean 'C'. There is no point in trying to define 3 to mean 3, since it already means 3. Make sense?

In Pascal, you can specify a type that holds only a specific ordered sequence with:

type Alphabet_t = 1..26;

Any variable declared with the type Alphabet_t can only have values in the range 1 to 26, inclusive.

C and C++ don't provide you with this ability (at least not directly), but it is a simple matter to check bounds.

assert( (1 <= a) && (a <= 26) );

That's the exact same thing that a Pascal compiler does for you when compiling.


Sometimes the two overlap a little, so C and C++ allow you to manipulate the actual value of enumerations, but such things are both rare(ish) and dangerous. Avoid it if you can and use constants instead. (Notice how the STL uses const values for such things and avoids enums altogether?)


Unless I'm way off base about your assignment, feel free to share this with your teacher. He should have prepared an assignment that better represents the concept.
I totally agree. Elements in an enumeration should have no relationship with each other such that they can be sorted in any ascending or descending order. Although both C and C++ allow values to be assigned to enumeration elements, I always think that if you find that you need to do this, then an enumeration is the wrong way to go, like Duoas says above, something like constants would be more suitable.
Topic archived. No new replies allowed.