VARIABLES WITH SPECIFIC SETS OF VALUES
You will sometimes be faced with the need for variables that have a limited set of possible values that can be usefully referred to by labels — the days of the week, for example, or months of the year, or the suits in a card deck. There is a specific facility in C++ to handle this situation, called an enumeration. There are two kinds of enumerations, those defined using the syntax used prior to the C++ 11 standard, and those defined using the syntax introduced by C++ 11. I’ll describe both because the old syntax is used widely, but the new syntax has several real advantages so you should only use that.
Old Enumerations
Take one of the examples I have just mentioned — a variable that can assume values corresponding to days of the week. You can define this as follows:
enum Weekdays{Mon, Tues, Wed, Thurs, Fri, Sat, Sun} today;
This declares an enumeration type with the name Weekdays and the variable today, which is an instance of the enumeration type Weekdays that can assume only the constant values specified between the braces. If you try to assign to today anything other than one of the set of values specified, it will cause an error. The symbolic names listed between the braces are known as enumerators. Each of the names of the days will be automatically defined as representing a fixed integer value that will be type int by default. The first name in the list, Mon, will have the value 0, Tues will be 1, and so on.
You could assign one of the ...
Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.