home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!iWarp.intel.com|eff!world!ksr!jfw
- From: jfw@ksr.com (John F. Woods)
- Newsgroups: comp.std.c
- Subject: Re: Scalars and Structs
- Keywords: casts
- Message-ID: <14333@ksr.com>
- Date: 31 Jul 92 13:05:26 EDT
- References: <1992Jul30.205601.13276@pasteur.Berkeley.EDU> <1992Jul31.110737.27892@nntpd.lkg.dec.com>
- Sender: news@ksr.com
- Lines: 44
-
- diamond@jit345.bad.jit.dec.com (Norman Diamond) writes:
- >In article <1992Jul30.205601.13276@pasteur.Berkeley.EDU> johnm@cory.Berkeley.EDU (John D. Mitchell) writes:
- >>ANSI Section 3.3.4 Cast Operators:
- >>Am I correct in taking this to mean that there is no way to cast a
- >>structure of known size to a scalar that just so happens to have the same
- >>size (or vice versa)?
- >Yes.
- >>Or is there a better solution. [than a union]
- >If the structure doesn't have storage class register, then you can do
- >*(scalar_type*)&structure.
-
- The Standard even guarantees that this must work; if the structure looks like
-
- struct something {
- scalar_type frobozz;
- } honk;
-
- then because "a pointer to a structure object, suitably converted, points to
- its initial member",
-
- *(scalar_type*)&structure
-
- is officially blessed.
-
- >If the scalar doesn't have storage class
- >register, then you can do *(structure_type*)&scalar.
-
- I'm much less sure about this one, in fact, I'm almost certain it's not
- guaranteed; if "scalar" is of type "char", then &scalar need not be maximally
- aligned, but the "all structure pointers smell alike" principle indicates that
- even
-
- struct {
- char frobozz;
- };
-
- can potentially require maximal alignment, hence
-
- *(struct_type*)&scalar;
-
- can detonate with an addressing error or indulge in other undesirable behavior.
- The standard guarantees that a pointer to the initial member of a structure
- object can be converted to a pointer to the structure, but *not* that a pointer
- to something of the same *type* may be so converted.
-