- [Instructor] C++ has an
enumerated type called enum
that's actually a really useful thing.
Here we have two enums,
and one of them
is for card suit,
Spade, Heart, Diamonds, Clubs
and one is for card ranks.
You notice we start at one
for this one,
Ace, Deuce, and then
we switch to
11 for Jack,
Queen and King.
And so this is kind of
how enums work.
If you don't specify
they tend to
start at zero although
that's not necessarily guaranteed,
but if you need them
to represent specific digits you can,
and then they go
sequentially from there
if you're not specifying.
And so what we have here is,
basically a deck of cards,
and you notice
I have this card deck.
My card type
is a structure with
a rank and a suit.
Each of them unsigned
8-bit integers
because we really don't have
to count any higher than 13,
and there's only 52
in the deck.
And so I can print
all of these cards out,
using this print card function.
And you notice
I have a switch
and I'm using these,
enums as constants.
And so I've got
Ace, Jack, Queen, King like that,
and suits, Spade, Heart, Diamonds and Clubs.
So while the enum looks,
syntactically like a type,
it's really not
even a type,
it's even referred to as a type,
but it's not really a type.
It works more
like a constant
and it makes
a great alternative
to preprocessor macros
which is how a lot of people
do things like this.
But with the enum
there are type safe.
And so here
I just go through the deck
with a for loop
and I print each card.
I can build this
and run it
and you see,
Ace, Deuce, and then
three, four, five, six, seven
and Jack, Queen, King.
And those are,
based on the switch statement
where I have
these strings, up here.
There's the Ace string
Jack, Queen and the suited strings.
And so as I loop
through the cards
I check each one,
if it matches
one of these enums
which is being used
as a constant,
then I can print out
that particular string.
So as you can see
enums can be really useful
for stuff like this.
For some uses,
constants may be
a better choice
if you need something
other than a scalar value,
but enum is often
a great alternative
to preprocessor constants
and for some uses
the enum type
can be very handy
for grouping scalar constants together
when they have a common usage,
as you see here,
with the ranks and suits.