Lesson 9 | Declarations and enumerated Types |
Objective | Explore the differences between how C and C++ declare enumerated types. |
Declarations and enumerated Types
In C++, you can declare tag names as types.
Let us write a card-shuffling program to illustrate C++ declarations. First, we define a card as a struct
:
enum suit { clubs, diamonds, hearts, spades };
struct card {
suit s;
int pips;
};
card deck[52]; //a declaration using card as the type
In ANSI C, the declaration of deck
would be illegal. It would have to be:
enum suit {clubs, diamonds, hearts, spades};
struct card {
enum suit s;
int pips;
};
struct card deck[52];
Do Tags Exist in C++?
In C++, the tag names are types.
Officially, the C++ standard does not recognize the notion of a tag name
(in this discussion the term "tag names" is used for convenience. It refers to class/struct/union names and enumerations in C++).
Unlike in C, you do not have to use the keywords struct, union and enum to instantiate objects.
Clarifying programs with enum
An enumerated data type is a way of attaching names to numbers, thereby giving more meaning to anyone reading the code. The
enum keyword (taken from C) automatically enumerates any list of identifiers you give it by assigning them values of 0, 1, 2.
You can declare enum variables (which are always represented as integral values). The declaration of an enum looks similar to a
struct declaration. An enumerated data type is useful when you want to keep track of some sort of feature:
// Keeping track of shapes
enum ShapeType {
circle,
square,
rectangle
}; // Must end with a semicolon like a struct
int main() {
ShapeType shape = circle;
// Now do something based on what the shape is:
switch(shape) {
case circle: /* circle stuff */ break;
case square: /* square stuff */ break;
case rectangle: /* rectangle stuff */ break;
}
} ///:~
shape is a variable of the ShapeType enumerated data type, and its value is compared with the value in the enumeration. Since shape
is really just an int, however, it can be any value an int can hold (including a negative number).
You can also compare an int variable with a value in the enumeration.
You should be aware that the example above of switching on type turns out to be a problematic way to program. C++ has a much
better way to code this sort of thing, the explanation of which must be delayed until much later in the book.
If you do not like the way the compiler assigns values, you can do it yourself using the following code:
enum ShapeType {
circle = 10, square = 20, rectangle = 50
};
If you give values to some names and not to others, the compiler will use the next integral value.
For example,
enum snap { crackle = 25, pop };
The compiler gives pop the value 26.
You can see how much more readable the code is when you use enumerated data types.
However, to some degree this is still an attempt (in C) to accomplish the things that we can do with a class in C++, so you will see enum used less in C++.