[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: gcc 3.4.4 cast warnings?
From: |
James Youngman |
Subject: |
Re: gcc 3.4.4 cast warnings? |
Date: |
Sat, 30 Jul 2005 15:55:28 +0100 |
User-agent: |
Mutt/1.5.9i |
On Sat, Jul 30, 2005 at 10:38:28AM +0200, Oskar Liljeblad wrote:
> He *was* compiling it using g++. Is there a GNU coding standard
> statement for 'void *' casts?
No, http://www.gnu.org/prep/standards/standards.html says nothing on
this subject. While some code in there does show a cast to char* for
the return value of malloc(), that could just as easily be a hangover
from the days when the system headers didn't always include a
declaration.
> If you look in the libc documentation you'll find casts for malloc
> in some places, some places not.
My strong recommendation would be that for C code casts from void*
should be avoided. The problem is that every time you make a cast to
(foo*) from some other type, you have set a trap for someone. In five
years when someone modifies the function that is being called to
return some type not compatible with (foo*), the compiler will not be
able to warn of the problem because the explicit cast silences the
warning. I much prefer software which is constructed in such a way as
to allow the compiler to help the programmer eliminate bugs.
Not having the cast will cause a problem for C++. For such cases if a
lot of use of C++ is planned, it may be worthwhile to consider a
wrapper function:
static
char* getbuffer(size_t siz)
{
#ifdef __cplusplus
return new char[siz];
// or
return (char*)malloc(siz);
#else
return malloc(siz);
#endif
}
static
char* discardbuffer(char *buf)
{
#ifdef __cplusplus
delete[] buf;;
// or
free(buf);
#else
free(buf);
#endif
}
Regards,
James.