home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / lang / cplus / 16213 < prev    next >
Encoding:
Internet Message Format  |  1992-11-13  |  1.8 KB

  1. Path: sparky!uunet!snorkelwacker.mit.edu!ai-lab!life.ai.mit.edu!tmb
  2. From: tmb@arolla.idiap.ch (Thomas M. Breuel)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: how to initilize an array inside of a class??
  5. Date: 13 Nov 92 10:25:06
  6. Organization: IDIAP (Institut Dalle Molle d'Intelligence Artificielle
  7.     Perceptive)
  8. Lines: 45
  9. Message-ID: <TMB.92Nov13102506@arolla.idiap.ch>
  10. References: <BxL3t2.FKG@ns1.nodak.edu>
  11. Reply-To: tmb@idiap.ch
  12. NNTP-Posting-Host: arolla.idiap.ch
  13. In-reply-to: cooper@plains.NoDak.edu's message of 12 Nov 92 03:46:14 GMT
  14.  
  15.    int some_ints[3000] = { 1, 6, 34, 3, ... ,0 };
  16.  
  17.    But my compiler complains about that, saying that I can't initialize
  18.    class members there.
  19.  
  20. I believe GNU C accepts something like that, but your code would
  21. be unportable.
  22.  
  23.    The only other way I can think of doing it is
  24.    to do something like:
  25.  
  26.    Y::Y()
  27.    {
  28.        some_ints[0] = 1;
  29.        some_ints[1] = 6;
  30.        ...
  31.        some_ints[2999] = 0;
  32.    }
  33.  
  34.    Is this my only other option??
  35.  
  36. Well, not quite. You could write:
  37.  
  38. static int some_ints_initial[] = { 1, 6, 34, 3, ..., 0};
  39.  
  40. Y::Y() {
  41.     copy_ints(some_ints,some_ints_initial,
  42.           sizeof some_ints_initial/sizeof *some_ints_initial);
  43. }
  44.  
  45.    Would there be a performance hit doing it that way, I kinda
  46.    think so as the first one is done at compile time, while the other is
  47.    done at run-time, correct??
  48.  
  49. Automatic variables always need to be initialized at runtime (that's a
  50. property of the machine, not of C).  The version that I gave above
  51. that uses "copy_ints" and "some_ints_initial" is pretty much what the
  52. compiler would generate anyway, and presumably, back in the days when
  53. C still cared about such things, K&R wanted you to be aware of this
  54. cost. In the brave new world of C++ where O(n) copying operations (and
  55. a lot of other stuff) happen behind your back anyway, this attitude is
  56. probably an anachronism.
  57.  
  58.                     Thomas.
  59.  
  60.