home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / comp / std / cplus / 1881 < prev    next >
Encoding:
Internet Message Format  |  1992-12-21  |  1.9 KB

  1. Xref: sparky comp.std.c++:1881 comp.std.c:3248
  2. Newsgroups: comp.std.c++,comp.std.c
  3. Path: sparky!uunet!taumet!steve
  4. From: steve@taumet.com (Steve Clamage)
  5. Subject: Re: Question about sizeof in C/C++.
  6. Message-ID: <1992Dec21.165858.8174@taumet.com>
  7. Organization: TauMetric Corporation
  8. References: <1992Dec3.195422.26393@cs.brown.edu> <1992Dec07.230924.20465@microsoft.com> <jamesc.724544278@bart> <jamesc.724907666@bart>
  9. Date: Mon, 21 Dec 1992 16:58:58 GMT
  10. Lines: 39
  11.  
  12. jamesc@swapsdev.state.state.COM.AU (James Cribb) writes:
  13.  
  14. >Suppose a single struct Something needed 7 bytes of memory.  For word
  15. >alignment, these might need to start on, say, 4-byte boundaries.
  16.  
  17. >E.g. (assume 4-byte floats),
  18.  
  19. >    struct Something
  20. >    {
  21. >        float  x;
  22. >        char  s[3];
  23. >    };
  24.  
  25. >Do the standards guarantee that sizeof(struct Something) will always be
  26. >8 rather than 7?
  27.  
  28. The C Standard (there isn't a C++ Standard yet) guarantees:
  29. - sizeof will return the amount of space reserved by the struct when it
  30.     is a member of an array;
  31. - each sub-object will be properly aligned;
  32. - there will be no unused space (padding) at the start of the struct.
  33.  
  34. There may be padding between members or at the end of the struct.  The
  35. size of the struct might be larger or smaller than the sum of the
  36. sizeof's of its members.  (The compiler might pack struct members more
  37. or less tightly than objects in an array.)
  38.  
  39. So if floats must start on a 4-byte boundary and sizeof(float)==4,
  40. then sizeof(struct Something) cannot be 7.  It must be some value
  41. greater than 7 which is a multiple of 4.  The most likely candidate
  42. is 8, but that is not guaranteed by the Standard.
  43.  
  44. For the case of C++ structs which are also legal C structs, the rules
  45. should be the same in the eventual C++ Standard.  That is, the intent
  46. (at the moment) is that a C struct should have the same size and memory
  47. layout when compiled by a compatible C++ compiler.
  48. -- 
  49.  
  50. Steve Clamage, TauMetric Corp, steve@taumet.com
  51.