typeof()

cottrell at nbs-vms.ARPA cottrell at nbs-vms.ARPA
Fri Feb 8 04:26:47 AEST 1985


/*
> 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?

I like it! However, you only have to change one of the `->' lines if
you do the following:

	typedef int *foo_t;
	foo_t foo;
	foo = (foo_t)malloc(sizeof(*foo) * nelts);

`Foo' is always of type `foo_t'. Be careful to keep from putting your
foo_t in your mout_h (like me) :-)
*/



More information about the Comp.lang.c mailing list