[comp.lang.c] Typeof operator in C

peter@ficc.uu.net (Peter da Silva) (01/13/90)

> This last sentence bothers me.  It would be quite simple to implement
> a C operator such as "(typeof) x" that returns some representation of
> the type of the variable x.

I think this would be a worthwhile innovation, and one that's as easy
to implement as sizeof. It wouldn't return a value, but would be used
anywhere a type could be used.

I realise this isn't quite what's meant here. An operator to return
some indication of the type of an object would be useful, but I'm not
sure what it'd return. A small integer? A structure? A pointer to a
structure? The "type" of a C object can be very complex... what would
it return for:

	struct {
		union uabc {
			struct {
				int a;
				int b;
			} ab;
			long c;
		} abc;
		union uabc *d;
		struct stat buf;
	} x;

But a typeof operator... wouldn't that be something...

#define SWAP(a,b) {typeof a tmp; tmp=a; a=b; b=tmp}
-- 
 _--_|\  Peter da Silva. +1 713 274 5180. <peter@ficc.uu.net>.
/      \
\_.--._/ Xenix Support -- it's not just a job, it's an adventure!
      v  "Have you hugged your wolf today?" `-_-'

brister@td2cad.intel.com (James Brister) (01/13/90)

In article <-K016ODxds13@ficc.uu.net> peter@ficc.uu.net (Peter da Silva) writes:
>   But a typeof operator... wouldn't that be something...
>
>   #define SWAP(a,b) {typeof a tmp; tmp=a; a=b; b=tmp}

Check out the GNU CC compiler. It has a ``typeof'' keyword that looks like
the ``sizeof'' keyword. It will take a type name or an expression and will
return some object that can be used anywhere a typedef name could be used:
e.g.

	typeof (*x) y

		declares y with the type of what x points to.

	typeof (*x) y[4]

		declares an array of such values

so the SWAP macro should work.

Just tried it and...

Script started on Fri Jan 12 18:18:33 1990
Welcome to /bin/tcsh
aries% cat test.c
#define SWAP(a,b) {typeof (a) tmp; tmp=a; a=b; b=tmp;}
int main () {
        int g=6 ,h=9 ;

        printf ("g = %d h = %d\n",g,h) ;
        SWAP (g,h) ;
        printf ("g = %d h = %d\n",g,h) ;
}
aries% gcc test.c
aries% a.out
g = 6 h = 9
g = 9 h = 6
aries% ^Dexit

script done on Fri Jan 12 18:18:55 1990
--
James Brister                                          brister@td2cad.intel.com
Intel Corp.                       {decwrl,oliveb}!intelca!mipos3!td2cad!brister

ted@nmsu.edu (Ted Dunning) (01/14/90)

In article <-K016ODxds13@ficc.uu.net> peter@ficc.uu.net (Peter da Silva) writes:

   But a typeof operator... wouldn't that be something...

   #define SWAP(a,b) {typeof a tmp; tmp=a; a=b; b=tmp}

from the documentation for the gcc extensions:

----------------------------------------------------------------
File: gcc  Node: Typeof, Prev: Naming Types, Up: Extensions, Next: Lvalues

Referring to a Type with `typeof'
=================================

Another way to refer to the type of an expression is with `typeof'.
The syntax of using of this keyword looks like `sizeof', but the
construct acts semantically like a type name defined with `typedef'.

There are two ways of writing the argument to `typeof': with an
expression or with a type.  Here is an example with an expression:

     typeof (x[0](1))

This assumes that `x' is an array of functions; the type described
is that of the values of the functions.

Here is an example with a typename as the argument:

     typeof (int *)

Here the type described is that of pointers to `int'.

If you are writing a header file that must work when included in ANSI C
programs, write `__typedef' instead of `typedef'.
*Note Alternate Keywords::.

A `typeof'-construct can be used anywhere a typedef name could be
used.  For example, you can use it in a declaration, in a cast, or inside
of `sizeof' or `typeof'.

   * This declares `y' with the type of what `x' points to.

          typeof (*x) y;

   * This declares `y' as an array of such values.

          typeof (*x) y[4];

   * This declares `y' as an array of pointers to characters:

          typeof (typeof (char *)[4]) y;

     It is equivalent to the following traditional C declaration:

          char *y[4];

     To see the meaning of the declaration using `typeof', and why it
     might be a useful way to write, let's rewrite it with these macros:

          #define pointer(T)  typeof(T *)
          #define array(T, N) typeof(T [N])

     Now the declaration can be rewritten this way:

          array (pointer (char), 4) y;

     Thus, `array (pointer (char), 4)' is the type of arrays of 4
     pointers to `char'.

--
She gave us wine, and set before us a dish composed of red pepper,
ground and mixed with corn meal, stewed in fat and water.  We could
not eat it.

  -- a kentucky mountain man's reaction to new mexican cuisine in the
     early 1800's.

bdb@becker.UUCP (Bruce Becker) (01/14/90)

In article <-K016ODxds13@ficc.uu.net> peter@ficc.uu.net (Peter da Silva) writes:
|> This last sentence bothers me.  It would be quite simple to implement
|> a C operator such as "(typeof) x" that returns some representation of
|> the type of the variable x.
|
|I think this would be a worthwhile innovation, and one that's as easy
|to implement as sizeof. It wouldn't return a value, but would be used
|anywhere a type could be used.
|[...]
|But a typeof operator... wouldn't that be something...
|
|#define SWAP(a,b) {typeof a tmp; tmp=a; a=b; b=tmp}

	I believe that much of what you speak of
	is contained in the PL/1 operator "LIKE",
	although I'm not sure if it applies to
	anything else but structures in that language.

	This example can be implemented in a similar
	fashion in PL/1 to the above...

-- 
  ,,,,	 Bruce Becker	Toronto, Ont.
w \$$/	 Internet: bdb@becker.UUCP, bruce@gpu.utcs.toronto.edu
 `/c/-e	 BitNet:   BECKER@HUMBER.BITNET
_/  >_	 "Money is the root of all money" - Adam

bph@buengc.BU.EDU (Blair P. Houghton) (01/14/90)

In article <-K016ODxds13@ficc.uu.net> peter@ficc.uu.net (Peter da Silva) writes:
>and Discredits someone else:
>> This last sentence bothers me.  It would be quite simple to implement
>> a C operator such as "(typeof) x" that returns some representation of
>> the type of the variable x.
>
>I think this would be a worthwhile innovation, and one that's as easy
>to implement as sizeof. It wouldn't return a value, but would be used
>anywhere a type could be used.
>
>I realise this isn't quite what's meant here. An operator to return
>some indication of the type of an object would be useful, but I'm not
>sure what it'd return. A small integer? A structure? A pointer to a
>structure? The "type" of a C object can be very complex... what would
>it return for:

              Where's the struct identifier?
              |
>	struct {
>		union uabc {
[...edited for television...]
>	} x;

Well, since you didn't give it a name, I'd expect it would
make one up and plop it on the symbol table.  And then
when you asked for typeof x, it would give back
`struct _T_aaa' or something similar.

>But a typeof operator... wouldn't that be something...
>
>#define SWAP(a,b) {typeof a tmp; tmp=a; a=b; b=tmp}

Oboy.  Saved a few char's in the source code...

				--Blair
				  "But what would it return for
				   `typeof( &a + &b )'? or is that
				   too daffy an idea?  Hi, Doug.:-)"

amull@Morgan.COM (Andrew P. Mullhaupt) (01/14/90)

In article <-K016ODxds13@ficc.uu.net>, peter@ficc.uu.net (Peter da Silva) writes:
> > This last sentence bothers me.  It would be quite simple to implement
> > a C operator such as "(typeof) x" that returns some representation of
> > the type of the variable x.
> 
> I think this would be a worthwhile innovation, and one that's as easy
> to implement as sizeof. It wouldn't return a value, but would be used
> anywhere a type could be used.
> 

Damn right it's useful. You can write concurrent assignment in 
general using ANSI standard C without this trick, but you need to 
go through a lot of alignment pain and type-defeating function calls
to get there. On some systems, you can get it all done for about a
two or threefold performance penalty. On the RISC chips, you're
totally nailed for a factor on the order of 30 (THIRTY). 

GNU C (gcc) has this little trick, and the performance penalty 
evaporates. but you don't even have to use the typeof function (?)
(It seems a little bit different than most C functions). You can
define a temporary variable for the value in say, a variable x by

typedef _type_of_x (x);  _type_of_x  temp_x = x;

Is there a down side to these facilities? (I.e. why didn't people
put 'em in ANSI? I'd really like to use GNU C, but it ain't likely
to show up in DOS or OS/2 this year, (or is it?)).

Later,
Andrew Mullhaupt

peter@ficc.uu.net (Peter da Silva) (01/15/90)

> Check out the GNU CC compiler. It has a ``typeof'' keyword that looks like
> the ``sizeof'' keyword.

Yes, seveal people have pointed me at GCC on this one.

> #define SWAP(a,b) {typeof (a) tmp; tmp=a; a=b; b=tmp;}
                            ^ ^

Are these parens needed? sizeof doesn't need tham.

Does GCC have my other favorite extensions?

	Anonymous aggregate constants. (execv(prog, (char *){"prog", ...})

	The BCPL valof operator. (a = valof { ... return b; }), also
known as the anonymous function.

Both of these were in BCPL, and the former is in PL/M as well...
-- 
 _--_|\  Peter da Silva. +1 713 274 5180. <peter@ficc.uu.net>.
/      \
\_.--._/ Xenix Support -- it's not just a job, it's an adventure!
      v  "Have you hugged your wolf today?" `-_-'

peter@ficc.uu.net (Peter da Silva) (01/15/90)

[ Note, I frequently leave off attributions where they're not needed,
  on the theory that you're less likely to flame a discussion if you
  don't know the principals. Is this to be a discussion of ideas or
  of personalities? ]

I said... what would typeof() return for some complex structure. This
being the typeof that returns a first-class object, not the typeof from
GCC 

> `struct _T_aaa' or something similar.

You mean it would return a string? That's an interesting idea. I would have
expected it to return a small integer of some sort. You know: _T_INT,
_T_CHAR, _T_DOUBLE.
-- 
 _--_|\  Peter da Silva. +1 713 274 5180. <peter@ficc.uu.net>.
/      \
\_.--._/ Xenix Support -- it's not just a job, it's an adventure!
      v  "Have you hugged your wolf today?" `-_-'

mike@umn-cs.CS.UMN.EDU (Mike Haertel) (01/15/90)

In article <-121H63ggpc2@ficc.uu.net> peter@ficc.uu.net (Peter da Silva) writes:
>I said... what would typeof() return for some complex structure. This
>being the typeof that returns a first-class object, not the typeof from
>GCC 

>> `struct _T_aaa' or something similar.

>You mean it would return a string? That's an interesting idea. I would have
>expected it to return a small integer of some sort. You know: _T_INT,
>_T_CHAR, _T_DOUBLE.

C has no run-time "type" type.  The type value of a typeof construct
exists only in the mind of the compiler.

-- 
Mike Haertel <mike@ai.mit.edu>
"Everything there is to know about playing the piano can be taught
 in half an hour, I'm convinced of it." -- Glenn Gould

peter@ficc.uu.net (Peter da Silva) (01/15/90)

> C has no run-time "type" type.  The type value of a typeof construct
> exists only in the mind of the compiler.

Yes, I know that. This discussion originated with a suggestion that such
a type be added to the language. It's kind of hard to see how the semantics
of such a thing could be standardised. What could one do with it at runtime?

The discussion about a typeof operator similar to the one in GCC developed
from that.
-- 
 _--_|\  Peter da Silva. +1 713 274 5180. <peter@ficc.uu.net>.
/      \
\_.--._/ Xenix Support -- it's not just a job, it's an adventure!
      v  "Have you hugged your wolf today?" `-_-'

gordon@sneaky.UUCP (Gordon Burditt) (01/15/90)

>I said... what would typeof() return for some complex structure. This
>being the typeof that returns a first-class object, not the typeof from
>GCC 
...
>You mean it would return a string? That's an interesting idea. I would have
>expected it to return a small integer of some sort. You know: _T_INT,
>_T_CHAR, _T_DOUBLE.

Ok, how about this extreme:  you pass this function a string,
the type of an argument (equivalent to typeof(typeof(anything)) ), and a 
pointer to that type:

typedef typeof(typeof(int)) type;
void errmsg(char *string, type argtype, void * argptr)
{
	switch(argtype)
	{
	/* How many of these should get "duplicate case value"? */
	case typeof(register char):
	case typeof(register signed char):
	case typeof(register unsigned char):
	case typeof(volatile register char):
	case typeof(volatile register signed char):
	case typeof(volatile register unsigned char):
		die("You can't pass a pointer to a register variable, dummy");
	case typeof(char): 
	case typeof(signed char):
	case typeof(unsigned char):
	case typeof(volatile char):
	case typeof(volatile signed char):
	case typeof(volatile unsigned char):
		.....
	case typeof(char *):
	case typeof(register char *):
	case typeof(unsigned char *):
	case typeof(signed char *):
		.....
	case typeof(char [1]):
	case typeof(char [2]):
		.....
	case typeof(struct bar):
		.....
	case typeof(typeof(int)):
		.....
	default:
		.....
	}
	....
	return;
}

You also get a number of compile-time or run-time functions that take a type 
and return a type:

pointerto(type) == the type of a pointer to type
functionreturning(type) == the type of a function returning type
deregisterize(type) == type with all "register" qualifiers removed
devolatileize(type) == type with all "volatile" qualifiers removed
basetype(type) == type with all "array of", "function returning", and
	"pointer to" removed.

Intel processors, will, of course, need Fat, Skinny, Obese, Normal, and
Anorexic sizes for the result of typeof().

					Gordon L. Burditt
					...!texbell!sneaky!gordon

bph@buengc.BU.EDU (Blair P. Houghton) (01/16/90)

In article <-121H63ggpc2@ficc.uu.net> peter@ficc.uu.net (Peter da Silva) writes:
>[ Note, I frequently leave off attributions where they're not needed,
>  on the theory that you're less likely to flame a discussion if you
>  don't know the principals. Is this to be a discussion of ideas or
>  of personalities? ]

INAPPROPRIATE FLAME ON!
Perhaps then you should instead leave off your .sig, since you
are about the only person on the whole of the net whom I'm likely
to flame on sight.

Credit those who wrote their words, especially when you agree
with them, and stop being so damn supercilious about the
purpose of the net.
INAPPROPRIATE FLAME OFF...

>I said... what would typeof() return for some complex structure. This
>being the typeof that returns a first-class object, not the typeof from
>GCC 
>
>> `struct _T_aaa' or something similar.
>
>You mean it would return a string? That's an interesting idea. I would have
>expected it to return a small integer of some sort. You know: _T_INT,
>_T_CHAR, _T_DOUBLE.

Sorry, let me clarify:


You had asked what the meaning of the typeof expression would be
if it were applied to this rather complicated struct you had
devised; my response was that there really was nothing to worry
about, since a struct can be recognized from its struct-identifier
(the optionial name that comes right after the word 'struct'
and right before the optional left-brace in the declaration)
and hence the compiler would only have to take the typeof
expression, evaluate it, and then replace the expression with
its value, which would be the type-identifier.  So, in the
case where you don't think up the identifier yourself, the
compiler would make up a unique one and use it.

typeof should return a type identifier, rather than a data value.

It's obviously useful in situations where you need to do a cast
or a declaration but don't know the type of the object you're
casting or creating.  Specifically, it fits perfectly in that
swap-macro you devised:

#define swap(a,b) {typeof a tmp; tmp = a; a = b; b = tmp}

where the expansion of

	int x,y;
	...
	swap(x,y);

gives

	{int tmp; tmp = x ...

where it wouldn't work if the typeof operator returned anything
that was data, even integer constants or strings.

Returning to the struct example, I was using `_T_aaa' as the
sort of nebulous name a compiler might choose as the identifier
of an otherwise un-identifier'ed struct, and then defining

	struct {
		...
	} x;

would mean that `typeof x' would return this thing from the
symbol table that was the type-identifier for the variable x,
which might come out in a debugger something like

	struct _T_aaa

				--Blair
				  "As long as we're making up operators,
				   if ( dollarsin pocket != 0 )..."

bph@buengc.BU.EDU (Blair P. Houghton) (01/16/90)

In article <JH216U4ggpc2@ficc.uu.net> peter@ficc.uu.net (Peter da Silva) writes:
FLAMES, AGAIN, SORRY:
[There you go again, Peter, pretending you know better than the rest of the
planet whether we should be able to see if you're flaming someone who
probably knew what he was talking about before you butchered his articles
and whom we can now not contact to ask more about their ideas because we
find yours repugnant...come on, are you that paranoid?]
FLAMES, AGAIN, DONE, I WISH...
>Someone else (whom peter doesn't respect) wrote:
>> C has no run-time "type" type.  The type value of a typeof construct
>> exists only in the mind of the compiler.
>
>Yes, I know that. This discussion originated with a suggestion that such
>a type be added to the language. It's kind of hard to see how the semantics
>of such a thing could be standardised. What could one do with it at runtime?

I get it.

Okay, so you want something that turns the type of an object
into data.

A `valoftypeof' operator?

(Of course, it would be called simply 'typeof' by the ANSI committee,
noting that it would have the two distinct meanings -- return a
type-specifier or return a data representation of the type-specifier --
depending on whether it appeared in a value- context or not...)

If it returns some integer, what does that integer mean,
and what would you do with it?

Obviously you're going to compare or display it, at least.

I thought at first that returning a string with at least
the string representation of the type-specifier would be
useful, but then you get into the usual problems of
defining string-constants and comparing them, but there
are mechanisms for that (strcmp(), et al), so it may be
sufficient to do so.

However, what if there's a gaffe and, say, two variables
of the same type are defined with separate declarations
neither of which carries an identifier?  e.g.:

	struct {
		int gobble;
	} dee;

	struct {
		int gobble;
	} gook;

Obviously dee and gook are the same type, but it would be a
wise (and damn slow) compiler indeed that could figure that
out and assign the same internal type-specifier to them both.

And it would be wrong for

	valoftypeof dee == valoftypeof gook

not to be 1.

So it would have to be either that the compiler would have
to match new types (which it can do anyway, or it wouldn't
be able to assign the value of dee to gook without complaining)
or the valoftypeof operator would have to return the entire
declaration less the variable identifier.

				--Blair
				  "It still says,
				   'error: dollarsin pocket: concept undefined'"

baud@eedsp.eedsp.gatech.edu (Kurt Baudendistel) (01/16/90)

GCC, the GNU C compiler, implements the ``typeof'' operator as it is being
discussed here. It allows an argument that can be an expression (an
r-value) or a type. The ``typeof'' construct can be used anywhere a typedef
name could be used (in any declaration or definition).

Be careful, however, of the nasty C preprocessor, which will make this
nice looking and appealing definition:


  #define SWAP(a,b) {typeof (a) tmp; tmp=a; a=b; b=tmp}
 
			[courtesy of peter@ficc.uu.net (Peter da Silva)]

fail in many cases, like

  if (x < y)
    SWAP (x, y);	// bracketing of SWAP makes the `;' extraneous
  else			// and fatal
    x = y;

or

  int tmp;
  ...
  SWAP (x, tmp);	// name ``tmp'' in SWAP makes this fail

or

  int a[10], b[10];
  ...
  SWAP (a, b);		// will this work? 
			// depends on your definition of `='

can you think of other pitfalls? 
kurt
-- 
Kurt Baudendistel --- GRA
Georgia Tech, School of Electrical Engineering, Atlanta, GA  30332
internet: baud@eedsp.gatech.edu         uucp: gatech!gt-eedsp!baud

davidsen@sixhub.UUCP (Wm E. Davidsen Jr) (01/16/90)

In article <5263@buengc.BU.EDU> bph@buengc.bu.edu (Blair P. Houghton) writes:

| >But a typeof operator... wouldn't that be something...
| >
| >#define SWAP(a,b) {typeof a tmp; tmp=a; a=b; b=tmp}
| 
| Oboy.  Saved a few char's in the source code...

  That's not what it's for. You have avoided a possible error caused by
changing the type of the items to be swapped. By forcing the temp to be
the same type as the items you avoid a type conversion, which could be
(a) slow and (b) might generate a roundoff or data loss error.

  Now my question (no gcc docs on this machine) is, does this return a
numeric value? In other words, can I improve my error checking in the
macro by saying something like:
	#define SWAP(a,b) {typeof a tmp;\
	assert(typeof a == typeof b);\
	tmp = a; a = b; b = tmp; }

  All this requires is that the evaluation return a discrete value for
all types, but the user defined types would be a problem. I can envision
a PRINT macro which would use typeof to select the format of the print.
I can envision it, and it's UGLY...
-- 
	bill davidsen - sysop *IX BBS and Public Access UNIX
davidsen@sixhub.uucp		...!uunet!crdgw1!sixhub!davidsen

"Getting old is bad, but it beats the hell out of the alternative" -anon

peter@ficc.uu.net (Peter da Silva) (01/16/90)

(for the folks on the sidelines... I'm flaming Blair P. Houghton. This
 will be my last posting on this particular topic. Followups are directed
 to alt.dev.null, "the ultimate moderated newsgroup". My apologies in
 advance. It probably won't happen again, certainly not in the next few
 months)

> [There you go again, Peter, pretending you know better than the rest of the
> planet whether we should be able to see if you're flaming someone who
> probably knew what he was talking about before you butchered his articles
> and whom we can now not contact to ask more about their ideas because we
> find yours repugnant...come on, are you that paranoid?]

Have you ever heard of the references line?

And I don't recall flaming anyone in this discussion. Until this message.

> Okay, so you want something that turns the type of an object
> into data.

No. I was merely pointing out that such an operator would have sticky
semantics. Thanks for explaining this in more detail.

Don't you suppose that since you can't even keep that point straight without
being distracted by people's names (as you said, you're inclined to flame
me on sight. This implies that you're easily distracted by labels), you've
made my point for me.
-- 
This .signature intentionally left blank.
-- 

uucibg@swbatl.UUCP (3929) (01/16/90)

In article <-K016ODxds13@ficc.uu.net> peter@ficc.uu.net (Peter da Silva) writes:
>> This last sentence bothers me.  It would be quite simple to implement
>> a C operator such as "(typeof) x" that returns some representation of
>> the type of the variable x.
>
>I think this would be a worthwhile innovation, and one that's as easy
>to implement as sizeof. It wouldn't return a value, but would be used
>anywhere a type could be used.
>
>I realise this isn't quite what's meant here. An operator to return
>some indication of the type of an object would be useful, but I'm not
>sure what it'd return. A small integer? A structure? A pointer to a
>structure? The "type" of a C object can be very complex... what would
>it return for:
>
>	struct {
>		union uabc {
>			struct {
>				int a;
>				int b;
>			} ab;
>			long c;
>		} abc;
>		union uabc *d;
>		struct stat buf;
>	} x;
>
>But a typeof operator... wouldn't that be something...
>
>#define SWAP(a,b) {typeof a tmp; tmp=a; a=b; b=tmp}

:-).  Implementing this is, of course, a rather complex task.  Certainly
doable, since this provides at least as much expressive power as operator
overloading in C++.  But by no means is it as easy to implement as sizeof.

>Peter da Silva. +1 713 274 5180. <peter@ficc.uu.net>.

But it sure would be nice...

--------------------------------------------------------------------------------
Brian R. Gilstrap    ...!{ texbell, uunet }!swbatl!uucibg OR uucibg@swbatl.UUCP
One Bell Center      +----------------------------------------------------------
Rm 17-G-4            | "Winnie-the-Pooh read the two notices very carefully,
St. Louis, MO 63101  | first from left to right, and afterwards, in case he had
(314) 235-3929       | missed some of it, from right to left."   -- A. A. Milne
--------------------------------------------------------------------------------
Disclaimer:
Me, speak for my company?  You must be joking.  I'm just speaking my mind.

Lynn.Lively@p4694.f506.n106.z1.fidonet.org (Lynn Lively) (01/17/90)

In an article of <15 Jan 90 03:21:53 GMT>, peter@ficc.uu.net (Peter da Silva)   
writes:

 Pd>From: peter@ficc.uu.net (Peter da Silva)
 Pd>Date: 15 Jan 90 03:21:53 GMT
 Pd>Organization: Xenix Support, FICC
 Pd>Message-ID: <JH216U4ggpc2@ficc.uu.net>
 Pd>Newsgroups: comp.lang.c
 Pd>
 Pd>> C has no run-time "type" type.  The type value of a typeof construct
 Pd>> exists only in the mind of the compiler.
 Pd>
 Pd>Yes, I know that. This discussion originated with a suggestion that 
 Pd>such
 Pd>a type be added to the language. It's kind of hard to see how the 
 Pd>semantics
 Pd>of such a thing could be standardised. What could one do with it at 
 Pd>runtime?
 Pd>
 Pd>The discussion about a typeof operator similar to the one in GCC 
 Pd>developed
 Pd>from that.

Peter,
     Excuse me if I'm answering out of turn, but wouldn't the above require 
a change in the basic philosophy of memory mapping in C? Seems to me in order
to implement such you would need a preamble in front of every field declaring
its 'type' and probably its 'size'. You would also need a dynamic symbol table   
 for user defined types via 'typedef'. This would cause a very fundemental    
change in the way you approached a problem in C and would IMHO cause more harm   
 than good as it would be alow more difficult to do such things as read in an
array of 'int's and then turn around and step thru the array with a 'char'    
pointer. Fields would no longer be layed out in contigious memory, passed
parameters to functions would need the preamble also causing alot of overhead    
for very little return. Seems to me the 'runtime type' is a good job for    
'union', don't you think?
Something like this.
typedef struct
  {
    int type;                  /* Could also use an 'enum' here */
    union
      {
        [various possible types]
      } u;
  } RT_TYPE;
Although a compile time 'typeof' would need less overhead (the compiler keeps   
this information anyway) and would have most of the advantages mentioned   
previously. I would very much like to see it, if it didn't take away from the   
power of C in other areas.
 Your Servant,
      Lynn

karl@haddock.ima.isc.com (Karl Heuer) (01/17/90)

Note: |typeof(x)| already exists, with that name, in gcc; it is syntactically
a type-name.  To avoid confusion, I'll refer to the original concept (an
operator that returns a value that somehow encodes the type information) as
|typecode(x)|.

>If it returns some integer, what does that integer mean, and what would you
>do with it?

My private library used to contain a function |void *alloc2(size_t, size_t)|
which would return a heap pointer that could be used like a two-dimensional
array.  The idea was that (int **)alloc2(m, n*sizeof(int)) would allocate and
return a single block of size m*sizeof(int *)+SLOP+m*n*sizeof(int), with the
first portion initialized to point into the last portion.  Then normal
subscripting |a[i][j]| would work, and the whole mess could be returned to the
freelist with a single call to |free()|.

I stopped using this function when I realized that it could not be implemented
on certain architectures.  (I'm willing to use library functions that cannot
be implemented portably, provided that they can be implemented nonportably on
any individual machine.  But this one can't be implemented *at all*, since
there exist two distinct results that take the same input.)  So instead I
started writing the necessary expansion inline, and bemoaned the fact that
this could never become a Standard Library function.

Or could it?  Suppose ANSI had mandated that a conforming implementation must
provide a macro |TYPE **malloc2d(size_t nr, size_t nc, TYPE)|.  Then a vaxlike
architecture simply has this expand into |(TYPE **)alloc2(nr,nc*sizeof(TYPE))|
where |alloc2()| is the function I described above.  Would this mean that
word-based architectures would be unable to implement ANSI C?  No, all that
they'd have to do is invent a minimal form of the |typecode()| operator, and
use |(TYPE **)alloc2x(nr,nc*sizeof(TYPE),typecode(TYPE *))| as the expansion,
where |alloc2x()| is like the impossible |alloc2()| except that it looks at
the third argument to decide whether to use char pointers or word pointers
when initializing the dope vectors.

Note that it's not necessary for |typecode| to actually distinguish among the
infinitely many types that can be constructed in C; all that is required *for
this application* is that any two pointer types with "different internal
representations" be distinguished.  On any particular architecture there are a
small number of these.

Let's return to the question.

>If it returns some integer, what does that integer mean, and what would you
>do with it?

If we were to agree that |typecode| is useful enough to actually require it
(in my example it was a "magic builtin" that the user would never need to know
about), I would say "implementation dependent".  More precisely, it should
return a value of type |typecode_t|, and it should be possible to compare two
such values for equality.  No other operations on |typecode_t| are necessary
or desirable.

Karl W. Z. Heuer (karl@haddock.isc.com or ima!haddock!karl), The Walking Lint

bph@buengc.BU.EDU (Blair P. Houghton) (01/18/90)

Before the fun starts, Ob. C:

Thanks to Andrew Koenig for giving me a well-deserved
refresher in paying attention to types, even seemingly
similar ones.  A pointer to an array has a very definite
difference from a pointer to the first element of the
array in pointer arithmetic, one manifestation of which,
of course, is

	*(elm1ptr + ARRAYSIZE) == *(arrayptr + 1)

And now for something completely unnecessary were it not for
the bad habits of some people:
In article <0A31K:Cggpc2@ficc.uu.net> peter@ficc.uu.net (Peter da Silva) writes:
>(for the folks on the sidelines... I'm flaming Blair P. Houghton. This

What else is new?

>> [There you go again, Peter, pretending you know better than the rest of the
>> planet whether we should be able to see if you're flaming someone who
>
>Have you ever heard of the references line?

Have you ever looked at one?  They contain site names and
either timestamps or serial numbers.  You tell me you can
email to the right person given only that info when their
article has dropped off the expiration cliff and I'll come
and kiss your superior-to-Bill-Joy feet.  Until then, you
can come and kiss my not-wiped-since-the-epoch ass.

>> Okay, so you want something that turns the type of an object
>> into data.
>
>No. I was merely pointing out that such an operator would have sticky
>semantics. Thanks for explaining this in more detail.

And the semantics are only sticky because [crude imagery
about Peter and chocolate ice cream omitted for the benefit
of our younger users --Blair] and because the problem
hadn't been stated very clearly.

>Don't you suppose that since you can't even keep that point straight without
>being distracted by people's names (as you said, you're inclined to flame
>me on sight. This implies that you're easily distracted by labels), you've
>made my point for me.

Labels are no problem.  Supercilious jerks who lack the
responsibility to attribute their sources are plagiarists,
and you in particular have shown throughout your entire
time on the net a predilection to ignore common courtesy
and custom.  I assume a defensive posture upon seeing you
the way I'd take my umbrella along on a dark and cloudy
day.  What was once a matter of conjecture is now a
probabilistic exercise with a simple, preemptive solution.

				--Blair
				  "I bet you pick your nose in
				   the grocery store, too."