In message <20020110201559$[EMAIL PROTECTED]>
          "Melvin Smith" <[EMAIL PROTECTED]> wrote:

> >  Foo foo = (Foo) malloc(sizeof(*foo));
> >? Does ANSI allow using sizeof on a variable declared on the
> > same line?
> 
> Wouldn't sizeof(Foo) be safer here? At the logical time of the
> call *foo points to undefined. Technically its not a deref but
> still looks scary. In C++ it might be confusing if you were to
> cast it as:

Well sizeof(Foo) and sizeof(*foo) are not actually the same thing
at all there because Foo is presumably a typedef for a pointer type
so sizeof(Foo) will be the size of a pointer and sizeof(*foo) will
be the size of the thing it points to.

You're quite right that it isn't technically a deref, as sizeof() is
only interested in the static type of the object and is evaluated at
compile time (if we ignore VLA's in C99 that is).

In general it is safer to sizeof() on the variable you are working
with than on it's type, as that way the sizeof() will still work if
somebody changes the type of the variable.

> // If it were really C++ we would probably be using new()
> Foo foo = (FooBar) malloc(sizeof(*foo));
> 
> What type is *foo then? Should be Foo, but what if FooBar
> was of different size, it might not be an obvious bug to someone
> that just came along and tweaked your code.

The type of *foo is whatever Foo as been typedefed as a pointer
to, and FooBar is a red herring.

> >If people have visceral objections to typedef'ing pointers, I'm
> >fine with dropping that part of the proposal. I'd just like to see
> 
> I've always been uncomfortable with that practice, its one part of
> the whole Win32 world I hate. If you stick with the practice then
> you either end up making a new typedef for every level of indirection
> or you drop to using * (some typedef), etc. Now if it were C++ and we
> were using a smart pointer class I don't mind the practice.

I will agreee that hiding pointers inside typedefs is not a very
good idea, if only because it makes it impossible to const qualify
the pointer without creating a second parallel typedef.

Tom

-- 
Tom Hughes ([EMAIL PROTECTED])
http://www.compton.nu/

Reply via email to