[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppEnum
Using enumerations, you can make your code more readable and natural. Below is first an example of NOT using enum, then followed by the enum equivalent.
This can be made more readable and type safe by:
Of course, the example without enum can be converted to the example below, using global constants. But why pollute the global namespace and lose the benefit of type safety (see also [1-4])?
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppEnum
(C++) enum
Keyword, being an abbreviation of enumeration.Using enumerations, you can make your code more readable and natural. Below is first an example of NOT using enum, then followed by the enum equivalent.
//Without using enum
void sayHello(const int& sex)
{
switch(sex)
{
case 0: std::cout << "(male voice) Hello!" << std::endl; break;
case 1: std::cout << "(female voice) Hello!" << std::endl; break;
case 2: std::cout << "(hermaphrodite voice) Hello!" << std::endl; break;
}
}
This can be made more readable and type safe by:
enum Sex { male, female, hermaphrodite };
void sayHello(const Sex& sex)
{
switch(sex)
{
case male: std::cout << "(male voice) Hello!" << std::endl; break;
case female: std::cout << "(female voice) Hello!" << std::endl; break;
case hermaphrodite: std::cout << "(hermaphrodite voice) Hello!" << std::endl; break;
}
}
Of course, the example without enum can be converted to the example below, using global constants. But why pollute the global namespace and lose the benefit of type safety (see also [1-4])?
//Without using enum
const int male = 0;
const int female = 1;
const int hermaphrodite = 2;
void sayHello(const int& sex)
{
switch(sex)
{
case male: std::cout << "(male voice) Hello!" << std::endl; break;
case female: std::cout << "(female voice) Hello!" << std::endl; break;
case hermaphrodite: std::cout << "(hermaphrodite voice) Hello!" << std::endl; break;
}
}
Code links
- #include
- scope operator'::'
- stream out operator '<<'
- assert
- char
- cout
- endl
- for
- #include
- int
- iostream
- main
- return
- scope operator'::'
- std
- stream out operator '<<'
- void
'enum' links
References
- 1) Herb Sutter,Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Chapter 10: 'Minimize global and shared data'.
- 2) Bjarne Stroustrup. The C++ Programming Language (3rd edition).ISBN: 0-201-88954-4. Chapter 1.8.2.a: 'Don't use global data (use members)'
- 3) Jarrod Hollingworth, Bob Swart, Mark Cashman, Paul Gustavson. Sams C++ Builder 6 Developer's Guide. ISBN: 0-672-32480-6. Chapter 3: 'Avoid using global variables'
- 4) Scott Meyers. Effective C++ (3rd edition).ISBN: 0-321-33487-6. Item 2: Prefer consts, enums and inlines to #defines
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
