[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
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

'enum' links

References



last edited (March 8, 2007) by bilderbikkel, Number of views: 4837, Current Rev: 12 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.