A useful construct for C ?

Eugene D. Brooks III brooks at lll-crg.ARPA
Tue Feb 5 10:42:26 AEST 1985


References:

I would like to sample the community on a possibly useful construct
	typeof(foo)
which is the type of expression foo.  It is similar in utility to sizeof().

When doing storage allocation with malloc the worst way to do it is:
	int *foo;
	foo = (int *)malloc(sizeof(int) * nelts);

A more sophisticated way of doing it is:
	int *foo;
	foo = (int *)malloc(sizeof(*foo) * nelts);

I like to use the above as I don't have to change the arguments to malloc
if I change the type declaration of foo.  I do have to change the type
cast to the new type however to keep lint happy.

It would be nice to be able to say:
	int *foo;
	foo = (typeof(foo))malloc(sizeof(*foo) * nelts);

In this case, if one changed the declaration of foo then one
would not have to change the executable line.

Yes, I do realize that you can come darn close to this.  You can put the two
lines you have to change together. Which is better than nothing.
	int *foo;
	typedef int *foo_t;
	foo = (foo_t)malloc(sizeof(*foo) * nelts);

But the typeof() construct would not require the typedef declaration!

Is such a typeof() construct available in C?  Should it be?



More information about the Comp.lang.c mailing list