CIS 250 - 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;