From: David Schwartz on
On Feb 26, 10:11 am, Rainer Weikusat <rweiku...(a)mssgmbh.com> wrote:

> It indicates to a reviewer that whoever wrote the code had a C/C++
> confusion problem.

There is nothing wrong with writing C code in C++ style, where
possible. For one thing, it makes it easier to port the code to C++ in
the future, should that be needed.

> The sole purpose of 'a pointer to void' in C is to
> have a generic pointer type which is assignment compatible with every
> other pointer type (minus pointers to functions), mostly for the
> reason that this enables easy use of memory allocation routines which
> do not allocated typed objects but storage areas of particular sizes.
>
> Usually, this will look like this:
>
>         struct blah *blah;
>
>         blah = malloc(sizeof(*blah));
>
> and the part a reviewer needs to look at is the argument to malloc,
> because it is completely possible to write
>
>         struct blah {
>                 double data[1748];
>         };                
>
>         struct blah *blah;
>
>         blah = (struct blah *)malloc(1);
>
> and this conversion is decidedly not correct.

Right. Now, any competent reviewer will know that 'malloc' returns a
'void *'. So this is impossible to miss. But compare:

blah = (struct foo *) barfl(1);
and
blah = barfl(1);

In the first case, what tells the reviewer that he has to make sure
that in this context, the 'void *' that 'barfl' returns can safely be
cast to a 'struct foo *'?

> > The advantages and disadvantages on both sides are quite comparable
> > and it is totally incorrect to argue that one way or the other is
> > clearly correct.

> A programming language usually has an annotation facility ('comments')
> with a specific syntax which explictly informs a read that a
> particular text is supposed to be documentation. This means someone
> who is really convinced that the fact that malloc does not return a
> pointer to an object of some type must be mentioned whenever malloc is
> used would be free to write
>
>         struct blah *blah;
>
>         /*
>           Remember that malloc allocates typeless
>           storage areas of a certains size.
>         */
>         blah = malloc(sizeof(*blah))
>
> This communicates the same information and doesn't have the downside
> that someone could accidentally confuse it with code which has
> presumably has a purpose.

There are many ways to skin a cat. I was simply comparing two of them.
There are definitely ways that are better than either of those two,
but the one you suggested above is not one of them.

A better one is a macro that:

1) Replaces to nothing in C code.
2) Replaces to a cast in C++ code.
3) Makes it obvious to a reviewer that a cast is going on.

DS