[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CEnum

(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.

  1. include <stdio.h>
//Without using enum void sayHello(int sex) { switch(sex) { case 0: sprintf("(male voice) Hello!"); break; case 1: sprintf("(female voice) Hello!"); break; case 2: sprintf("(hermaphrodite voice) Hello!"); break; } }


This can be made more readable and type safe by:
enum Sex { male, female, hermaphrodite };
void sayHello(Sex sex)
{
  switch(sex)
  {
    case male: 
      sprintf("(male voice) Hello!");
      break;
    case female:     
      sprintf("(female voice) Hello!");
      break;
    case hermaphrodite: 
      sprintf("(hermaphrodite voice) Hello!");
      break;
  }
}


Of course, the example without enum can be converted to the example below, using macros. But why lose the benefit of type safety?

  1. include <stdio.h>
  1. define MALE 0
  2. define FEMALE 1
  3. define HERMAPHRODITE 2
//Without using enum void sayHello(int sex) { switch(sex) { case MALE: sprintf("(male voice) Hello!"); break; case FEMALE: sprintf("(female voice) Hello!"); break; case HERMAPHRODITE: sprintf("(hermaphrodite voice) Hello!"); break; } }


Code links

'enum' links



last edited (March 8, 2007) by bilderbikkel, Number of views: 926, Current Rev: 2 (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.