|
From: Bob W. <bo...@ph...> - 2002-04-20 21:30:44
|
MessageIoannis,
Absolutely correct, but when you assign a value to an enumerated =
element, it practically destroys or greatly limits the ability to use =
the enumerated elements in a for loop or switch statement. =20
Why you can't use them in a switch statement? In fact a switch =
statement is one of the common uses for enums.
If you will re-read what I wrote, you will see I did not say you could =
not use them, however, if you write something like this:
enum animals { cat, dog, horse =3D 7, rabbit =3D 3, pig, cow, mule =3D =
30 }
which is a legal statement, and you write a for loop like this:
int counter;
for (counter =3D cat - 1; counter < mule; counter++)
{
std::cout << "counter =3D " << counter << "\n"
};
The loop will execute 30 times even though there are only seven =
elements. It works, but it can lead to unexpected results if you think =
is it only going to loop seven times because there are only seve =
elements. If no value assignments are given to the set of elements, the =
loop works as a novice might expect. It is certainly possible that there =
is an operation that must not be performed for a cat, once for a dog, =
seven times for a horse, three times for a pig, four times for a cow, =
and 30 times for a mule, and, in that case, you could make the for work. =
However, I doubt that the resulting code would be a decypherable as =
using conditional switching to call an offset function as follows:
#include <iostream.h>
#include <stdlib.h>
enum animals { cat, dog, horse =3D 7, rabbit =3D 3, pig, cow, mule =3D =
30 };
int DoItNow (int NumOfTimes)
{
for (int i =3D cat; i < NumOfTimes; i++)
{
// do something
std::cout << "did something " << i + 1 << " times\n";
}
};
int main()
{
unsigned short int whichAnimal;
std::cout << "Enter a number between "=20
<< cat << " and " << mule << ": ";
std::cin >> whichAnimal;
std::cout << "Hey! It's a";
switch (whichAnimal)
{
case cat : std::cout << " cat!\n";
DoItNow(cat); // do it once
break;
case dog : std::cout << " dog!\n";
DoItNow(dog); // do it twice
break;
case horse : std::cout << " horse!\n";
DoItNow(horse); // do it seven times
break;
case rabbit : std::cout << " rabbit!\n";
DoItNow(rabbit); // do it three times
break;
case pig : std::cout << " pig!\n";
DoItNow(pig); // do it four times
break;
case cow : std::cout << " cow!\n";
DoItNow(cow); // do it five times
break;
case mule : std::cout << " mule!\n";
DoItNow(mule); // do it 30 times
break;
default:
std::cout << "n unidentified animal!\n"; // fall through
}
=20
system("pause");
return 0;
}
To me, it is much easier to see that the programmer wants an activity to =
take place seven times if the value is horse than using whichAnimal in =
the for loop above. Obviously the code is not as tight, but it is =
certainly more transparent which is a good thing.=20
Regards,
Bob
|