home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / std / c / 2401 < prev    next >
Encoding:
Internet Message Format  |  1992-07-31  |  1.8 KB

  1. Path: sparky!uunet!iWarp.intel.com|eff!world!ksr!jfw
  2. From: jfw@ksr.com (John F. Woods)
  3. Newsgroups: comp.std.c
  4. Subject: Re: Scalars and Structs
  5. Keywords: casts
  6. Message-ID: <14333@ksr.com>
  7. Date: 31 Jul 92 13:05:26 EDT
  8. References: <1992Jul30.205601.13276@pasteur.Berkeley.EDU> <1992Jul31.110737.27892@nntpd.lkg.dec.com>
  9. Sender: news@ksr.com
  10. Lines: 44
  11.  
  12. diamond@jit345.bad.jit.dec.com (Norman Diamond) writes:
  13. >In article <1992Jul30.205601.13276@pasteur.Berkeley.EDU> johnm@cory.Berkeley.EDU (John D. Mitchell) writes:
  14. >>ANSI Section 3.3.4 Cast Operators:
  15. >>Am I correct in taking this to mean that there is no way to cast a
  16. >>structure of known size to a scalar that just so happens to have the same
  17. >>size (or vice versa)?
  18. >Yes.
  19. >>Or is there a better solution. [than a union]
  20. >If the structure doesn't have storage class register, then you can do
  21. >*(scalar_type*)&structure.
  22.  
  23. The Standard even guarantees that this must work; if the structure looks like
  24.  
  25.     struct something {
  26.         scalar_type frobozz;
  27.     } honk;
  28.  
  29. then because "a pointer to a structure object, suitably converted, points to
  30. its initial member", 
  31.  
  32.     *(scalar_type*)&structure
  33.  
  34. is officially blessed.
  35.  
  36. >If the scalar doesn't have storage class
  37. >register, then you can do *(structure_type*)&scalar.
  38.  
  39. I'm much less sure about this one, in fact, I'm almost certain it's not
  40. guaranteed; if "scalar" is of type "char", then &scalar need not be maximally
  41. aligned, but the "all structure pointers smell alike" principle indicates that
  42. even
  43.  
  44.     struct {
  45.         char frobozz;
  46.     };
  47.  
  48. can potentially require maximal alignment, hence
  49.  
  50.     *(struct_type*)&scalar;
  51.  
  52. can detonate with an addressing error or indulge in other undesirable behavior.
  53. The standard guarantees that a pointer to the initial member of a structure
  54. object can be converted to a pointer to the structure, but *not* that a pointer
  55. to something of the same *type* may be so converted.
  56.