Enumerations

Objectives

  • Create and use enumerations
  • Use a typedef
  • Create and use a namespace

Declaring an enumeration

  • Declaring an enum: enum enumname { identifierList };
  • Example: enum suit { DIAMONDS, CLUBS, HEARTS, SPADES };
  • Identifiers have to follow standard identifier naming rules
  • Identifiers have int values internally
  • You are guaranteed that identifiers increase in value as you go to the right
  • You can assign a specific identifier in the list a value
  • If unspecified, enum numbering starts at 0 and increases by 1 for each identifier

Using an enum

  • Declaring a variable: enumName variableName;
  • Example: suit cardSuit;
  • Example of assigning a value: cardSuit = HEARTS;
  • No standard arithmetic operations are allowed on enumerations
  • You can increment an enum doing the following: cardSuit = static_cast<suit>(cardSuit + 1)
  • You can decrement an enum doing the following: cardSuit = static_cast<suit>(cardSuit - 1)
  • Relational operators work fine with enumeration variables/values
  • For loops work well with enumerations, but remember that the increment and decrement is done a little differently
  • Enumeration values can be passed to and returned from functions
  • Enumeration values can be used as switch statement values
  • You can specify a list of variable names at the end of an enum declaration
  • You can omit the enumeration name, but then it becomes hard to use in your code
  • Value names used in one enum are internally unique from value names used in another enum, even if the value names appear the same to us

typedef

  • typedef is used to create synonyms/aliases to a previously defined type
  • Example: typedef int Boolean;
  • Example: const Boolean TRUE = 1;
  • Example: const Boolean FALSE = 0;

namespace

  • Create a namespace: namespace namespaceName { members }
  • Using a namespace member: namespaceName::namespaceMember
  • Namespace members can include variables, constants, and functions
  • To make all members of a namespace available: using namespace namespaceName;
  • To make a single member of a namespace available: using namespaceName::memberName;