Hi, i am confused with using enu. Hopefully the expert here can solve my dobut. I dont understand the benefits of using it.
For example
Code:
enum e_acomany {
Audi,
BMW,
Cadillac,
Ford,
Jaguar,
Lexus
Maybach,
RollsRoyce,
Saab
};
e_acompany my_car_brand;
my_car_brand = RollsRoyce;
//...
if (my_car_brand == Ford)
cout << "Hello, Ford-car owner!" << endl;
why cant i do like this?
string ford;
if (my_car_brand == Ford)
cout << "Hello, Ford-car owner!" << endl;
In this example,
How to use Enums in C++ - Stack Overflow
when or rather how to use the full stop?
Before enumeration is available in programming languages, we normally use constructs such as preprocessor definition in K&R C.
Code:
#define APPLE 1
#define ORANGE 2
#define PEAR 3
Then in the code we can write things like
Code:
int fruit = ...;
if (fruit == APPLE) {
printf("I got an apple\n");
else
...
The idea is to turn your code into a self explanatory manner rather than this
Code:
int fruit = ...;
if (fruit == 1) {
printf("I got an apple\n");
else
...
But still using preprocessor definition is not good enough, because it lacks something called Typing.
Suppose I write this
Code:
int car = ...;
if (car == APPLE) ...
In K&R C, this will work just fine. Because after all APPLE Is just a text replacement performed by the preprocessor(okay too simple to just call it text replacement).
So when it arrives at the compiler, it sees
Code:
int car = ...;
if (car == 1) ...
Which is semantically correct and hence let it pass. But obviously from a higher order of understanding the intention of the codes, it is wrong since we will not likely attempt to test a car against an apple concept.
Hence with proper typing, enumerations helps to provide clarity by providing typing as such
Code:
enum Fruits { APPLE, ORANGE, PEAR };
Fruits fruit;
fruit = ...;
if (fruit == APPLE) {
...
}
It is analogous to "int" type, I can express the same code above when use as an integer (not syntactically correct)
Code:
enum Integer { ..., -3, -2, -1, 0, 1, 2, 3, ... };
Integer number;
number = ...;
if (number == 2) {
...
}
I hope you get the idea well, Unfortunately I'm not going to write out the full possible range of the 32/64bits integer type.
One thing if you are a Java programmer introduced in the language since version 5, the behaviour is different since printing out a enumeration type display the actual label in text rather than the numerical representation assigned to it.
There are changes along the way how enumeration are interpreted and today even ANSI C have enumeration already. So it can be confusing, read more up at
Enumerated type - Wikipedia, the free encyclopedia