using enum

I don´t really understand the use of enum. I guess its purpose is to simplify human understending of code, since it allows to replace sheer numbers with miningful words.
So I create an enum:

1
2
3
4
5
6
7
enum COLOR 
{
   BLACK,
   WHITE,
   RED,
   //...
};


and now I can store information using BLACK as a value (0 for the computer), or RED (that would be 2).

My question is:
Can I get the word RED by providing number two?

Can I ask the computer to show me the actual word?

Am I asking something enum does not do?

I guess that would be a map, what I´m asking...
I think you meant character literals instead of words.
The answer is no. These names are known only at compilation time. What you are saying about is present in C#.

For example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;

namespace TestEnum
{
    enum Color { Red, Green, Blue };

    class Program
    {
        static void Main(string[] args)
        {
            var c = Color.Red;

            Console.WriteLine("{0:d} is {0}",c);
        }
    }
}


The output is

0 is Red
Last edited on
Here are some useful links regarding enums.
http://www.cplusplus.com/forum/beginner/44859/
http://www.cplusplus.com/doc/tutorial/other_data_types/

For the sake of this argument, think of an enum as a set of integers. You can't output the name you chose for the variable in the program because that doesn't exist after compile time. So no, you can't output the actual word in that sense.

What you are describing does require a map.
Or another C# example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;

namespace TestEnum
{
    enum Color { Red, Green, Blue };

    class Program
    {
        static void Main(string[] args)
        {
            Array enumData = Enum.GetValues( typeof( Color ) );

            for ( int i = 0; i < enumData.Length; i++ )
            {
                Console.WriteLine("{0:d} is {0}", enumData.GetValue(i));
            }
        }
    }
}


The output is

0 is Red
1 is Green
2 is Blue
In C++ you can define a character array with names of enumerators and use them as indexes in the array. For example

1
2
3
4
enum { BLACK, WHITE, RED };
const char *ColorNames[] = { "BLACK", "WHITE", "RED" };

std::cout << BLACK << " is " << ColorNames[BLACK] << std::endl;

Last edited on
Thak you for the information, the links and the C# code!!! I´m going to read the links and maybe post better informed questions then, thanks again!
Now I get it better, specially from that old forum thread. I was lacking good examples of its use, and I was trying also to have the user input the enumeration values straightforward. Thank you, Thumper!
Topic archived. No new replies allowed.