[linux-elitists] Nobody's favorite language? C++ and free software

Martin Pool mbp@sourcefrog.net
Tue Apr 1 14:57:47 PST 2003


On  1 Apr 2003, Aaron Sherman <ajs@ajs.com> wrote:
> On Wed, 2003-03-26 at 16:54, Martin Pool wrote:
> 
> > The thing I would most like in C is const_cast, reinterpret_cast,
> > etc.  That could make it a lot safer.  Perhaps they could be done as
> > some kind of gcc attribute(())-like system.
> 
> The distinction was required in C++ because of run-time type
> identification, required for certain types of templated
> polymorphism. 

I know.

> I don't see the need in C. Please feel free to explain how you would
> use it, as I'm willing to believe that I could be way off base here.

Here's one example: sometimes in C, you need to cast from, say, a (char
**) to a (const char **), or a (const char *) to a (char *)
  
  blah (const char *a)
  {
     squidge ((char *) a);
  }

The problem is that in C, there is only one cast operator, and it is
very powerful.  If it later happened that 'a' changed into something
other than a (const char *), then you'd get no warning, it would just
be forced across, possibly giving you an invalid pointer.

It would be nice if you could tell the compiler what you're trying to
do with the cast, so that it could warn you if you make a mistake.  I
know gcc tries to issue some warnings at the moment but they're not
very strong.  It could distinguish

 - just changing constness
 - actually reinterpreting bytes
 - perhaps some other cases

Actually, what might be nice in gcc would be an option to prevent you
ever casting from one incompatible pointer type to another, without
going via (void *).  That might make the intention to reinterpret
memory more clear.

-- 
Martin



More information about the linux-elitists mailing list