Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site brl-tgr.ARPA Path: utzoo!watmath!clyde!burl!ulysses!allegra!mit-eddie!godot!harvard!seismo!brl-tgr!tgr!cottrell@nbs-vms.ARPA From: cottrell@nbs-vms.ARPA Newsgroups: net.lang.c Subject: typeof() Message-ID: <8112@brl-tgr.ARPA> Date: Thu, 7-Feb-85 13:26:47 EST Article-I.D.: brl-tgr.8112 Posted: Thu Feb 7 13:26:47 1985 Date-Received: Sun, 10-Feb-85 04:09:27 EST Sender: news@brl-tgr.ARPA Organization: Ballistic Research Lab Lines: 44 /* > 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) :-) */