[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CEnum
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 macros. But why lose the benefit of type safety?
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
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.
//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; } }
- include <stdio.h>
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?
- include <stdio.h>
//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; } }
- define MALE 0
- define FEMALE 1
- define HERMAPHRODITE 2
Code links
'enum' links
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
