home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!taumet!steve
- From: steve@taumet.com (Steve Clamage)
- Subject: Re: Problems with int as enum
- Message-ID: <1992Sep14.173619.9919@taumet.com>
- Organization: TauMetric Corporation
- References: <1992Sep13.222623.21562@ra.msstate.edu>
- Date: Mon, 14 Sep 1992 17:36:19 GMT
- Lines: 57
-
- cee1@ra.msstate.edu (Charles Evans) writes:
-
- >int random(void);
-
- >enum suit { clubs, diamonds, hearts, spades };
-
- >struct card { suit s; int pips };
- -------------------------------^ <----------------
- >...
-
- >void init_deck(card d[])
- >{
- > for (int i = 0; i < 52; ++i)
- > {
- > d[i].s = (i / 13); // enum as int ? -- WARNING #1
- > d[i].pips = 1 + i % 13;
- > }
- >}
- >void shuffle(card d[])
- >{
- > for (int i = 0; i < 52; ++i)
- > {
- > int k = random() % 52 // choose a random card
- -------------------------------------^ <----------------
- > card t = d[i]; // swap two cards ERROR #2, #3
- > d[i] = d[k];
- > d[k] = t; // ERROR #4
- > }
- >}
-
- You are missing semicolons at the two marked places. The second one
- is the cause of errors 2, 3, and 4.
-
- Warning #1 is exactly what it says. You are assigning an int value
- to an enum object. You can turn off the warning with an explicit
- cast, but the practice is still dangerous. If you make any change
- in the definition of "suit", the code may continue to compile but
- may not run correctly.
-
- Example: Suppose you change the definition to
- enum suit { clubs = -2, diamonds = -1, hearts = +1, spades = +2 };
- so that red/black can be determined by "abs(s)==1" and major/minor
- can be determined by sign. The code which naively assigns integer
- values could wind up with impossible enum values.
-
- It is safer to do something like
- switch( expression ) {
- case clubs: s = clubs; break;
- case diamonds: s = diamonds; break;
- case hearts: s = hearts; break;
- case spades: s = spades; break;
- }
- This code is always correct, no matter how the definition of suits changes.
- --
-
- Steve Clamage, TauMetric Corp, steve@taumet.com
- Vice Chair, ANSI C++ Committee, X3J16
-