home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #20 / NN_1992_20.iso / spool / comp / lang / cplus / 13625 < prev    next >
Encoding:
Text File  |  1992-09-14  |  2.0 KB  |  68 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!taumet!steve
  3. From: steve@taumet.com (Steve Clamage)
  4. Subject: Re: Problems with int as enum
  5. Message-ID: <1992Sep14.173619.9919@taumet.com>
  6. Organization: TauMetric Corporation
  7. References: <1992Sep13.222623.21562@ra.msstate.edu>
  8. Date: Mon, 14 Sep 1992 17:36:19 GMT
  9. Lines: 57
  10.  
  11. cee1@ra.msstate.edu (Charles Evans) writes:
  12.  
  13. >int random(void);
  14.  
  15. >enum suit { clubs, diamonds, hearts, spades };
  16.  
  17. >struct card { suit s; int pips };
  18. -------------------------------^    <----------------
  19. >...
  20.  
  21. >void init_deck(card d[])
  22. >{
  23. >    for (int i = 0; i < 52; ++i)
  24. >    {
  25. >        d[i].s = (i / 13);   // enum as int ? -- WARNING #1
  26. >        d[i].pips = 1 + i % 13;
  27. >    }
  28. >}
  29. >void shuffle(card d[])
  30. >{
  31. >    for (int i = 0; i < 52; ++i)
  32. >    {
  33. >        int k = random() % 52     // choose a random card
  34. -------------------------------------^    <----------------
  35. >        card t = d[i];        // swap two cards ERROR #2, #3
  36. >        d[i] = d[k];
  37. >        d[k] = t;        // ERROR #4
  38. >    }
  39. >}
  40.  
  41. You are missing semicolons at the two marked places.  The second one
  42. is the cause of errors 2, 3, and 4.
  43.  
  44. Warning #1 is exactly what it says.  You are assigning an int value
  45. to an enum object.  You can turn off the warning with an explicit
  46. cast, but the practice is still dangerous.  If you make any change
  47. in the definition of "suit", the code may continue to compile but
  48. may not run correctly.
  49.  
  50. Example: Suppose you change the definition to 
  51.     enum suit { clubs = -2, diamonds = -1, hearts = +1, spades = +2 };
  52. so that red/black can be determined by "abs(s)==1" and major/minor
  53. can be determined by sign.  The code which naively assigns integer
  54. values could wind up with impossible enum values.
  55.  
  56. It is safer to do something like
  57.     switch( expression ) {
  58.         case clubs:    s = clubs;     break;
  59.         case diamonds: s = diamonds; break;
  60.         case hearts:   s = hearts;     break;
  61.         case spades:   s = spades;     break;
  62.     }
  63. This code is always correct, no matter how the definition of suits changes.
  64. -- 
  65.  
  66. Steve Clamage, TauMetric Corp, steve@taumet.com
  67. Vice Chair, ANSI C++ Committee, X3J16
  68.