🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #178

Re: Scalars and Structs

#178
From: John F. Woods
Date: Fri, 31 Jul 1992 17:05
44 lines
1941 bytes
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.
Technical Details
Message-ID: <14333@ksr.com>
Path: arc1-ca.pugleaf.net!sparky!uunet!iWarp.intel.com|eff!world!ksr!jfw
References: <1992Jul30.205601.13276@pasteur.Berkeley.EDU> <1992Jul31.110737.27892@nntpd.lkg.dec.com>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!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