Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP
Path: utzoo!mnetor!uunet!husc6!think!barmar
From: barmar@think.COM (Barry Margolin)
Newsgroups: comp.lang.c
Subject: Re: How to discriminate the structures?
Message-ID: <12662@think.UUCP>
Date: Thu, 3-Dec-87 16:10:45 EST
Article-I.D.: think.12662
Posted: Thu Dec  3 16:10:45 1987
Date-Received: Mon, 7-Dec-87 06:02:40 EST
References: <420@slb-sdr.UUCP>
Sender: usenet@think.UUCP
Reply-To: barmar@sauron.UUCP (Barry Margolin)
Organization: Thinking Machines Corporation, Cambridge, MA
Lines: 62
Keywords: structure, typeof()

In article <420@slb-sdr.UUCP> saito@slb-sdr.UUCP (Naoki Saito) writes:
>	A few weeks ago, there was a discussion on typeof() on this news group.
>I would like to use typeof() if someone has a code of that.
>What I want to do is to discriminate type of the structured variables.
>For example,
>
>typedef struct {
>	float x;
>	float y;
>} POINT;
>
>typedef struct {
>	float r;
>	float theta;
>} POINTR;
>
>foo(point)
>     caddr_t *point; /* In fact, I don't know how to declare point here. */
>		     /* caddr_t is "character address type" used in Sun. */
>{
>  if (typeof(*point) == POINT)
>    { do something...}
>  else if (typeof(*point) == POINTR)
>    { do something...}
>}

If typeof existed, it would have to be built into the compiler, it
couldn't be a library subroutine.  And typeof(*point) would be
caddr_t, not POINT nor POINTR.

C doesn't have runtime data type tagging (a particular implementation
could, but a program that depended on it would not be portable).  The
type of a variable is whatever it is declared to be.  Stricly
speaking, a caller of foo() is required to cast his POINT* or POINTR*
parameter to caddr_t*, e.g.

	POINTR this_point;

	foo ((caddr_t *) &this_point);

So even if the data type were passed in the call, it would pass
caddr_t*, not the specific type.

Someone else already responded suggesting passing an additional
argument to foo to discriminate.  An alternative would be to include a
discriminant in your structure, e.g.

	typedef struct {
		enum {xy, rtheta} type;
		union {POINT, /* when type == xy */
		       POINTR} /* when type == rtheta */
	} GENERAL_POINT;

(please excuse any syntax errors, I don't do much C programming).
Then instead of using typeof(point) you use point.type.

---
Barry Margolin
Thinking Machines Corp.

barmar@think.com
seismo!think!barmar