[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Bug-gnulib] Re: avoid using casts whenever possible [Re: gnulib/lib err
From: |
Paul Eggert |
Subject: |
[Bug-gnulib] Re: avoid using casts whenever possible [Re: gnulib/lib error.c |
Date: |
29 Sep 2003 12:40:16 -0700 |
User-agent: |
Gnus/5.09 (Gnus v5.9.0) Emacs/21.3 |
Bruno Haible <address@hidden> writes:
> 1) It allows to do the usual code reorganizations without thinking about
> types. For example, the typical "replace variable that is only used
> once with its initial value" reorganization
>
> char *p = xmalloc (strlen (s));
> return strcpy (p, s);
>
> -->
>
> return strcpy (xmalloc (strlen (s)));
>
> produces a warning.
I don't understand this point. I assume you mean the following rewrite:
char *p = xmalloc (strlen (s) + 1);
return strcpy (p, s);
->
return strcpy (xmalloc (strlen (s) + 1), s);
But this rewrite results in valid C code; it shouldn't produce a
warning, any more than the original code did. (Hmm, perhaps you're
referring to a C++ warning? Then please see below.)
> 2) Suddenly the need can arise to use a C++ compiler for C code
That would be a reasonable practical motivation, if it happens that
C++ compilers are used often to compile GNU applications, and we want
to cater to such compilers to encourage the spread of free software.
But I'm a bit dubious about making C++ compatibility a goal for all
gnulib code. I don't think it's too much these days to ask people to
use C compilers, or at least to use C++ compilers that compile
standard C89 constructs as extensions. So I don't see C++
compatibility as being a significant help to promoting the use of
gnulib code.
> > IMHO, casts in C make code *less* maintainable because the type of
> > the cast often must agree with that of a related variable, and there
> > is no mechanism to ensure that they stay in sync.
>
> Sure there is a mechanism:
The compiler will catch some type errors but it won't catch all of
them, because in C casts are usually a stronger mechanism than what is
needed. For example, if I mistakenly think a pointer N is an integer,
and cast N to size_t by mistake, the compiler won't complain (on the
vast majority of platforms, anyway); but if I instead assign N to a
size_t variable without a cast, the compiler will diagnose the error.
> One uses the XMALLOC macro in the form it was before Paul's
> 2003-07-22 patch.
(Just for the record: I installed that patch, but it was Jim's idea. :-)
As I mentioned in an earlier message, I don't like XMALLOC (either the
old or the new form), because it is a function-style macro but it does
not behave like a function. I think we should get rid of it, even if
we lose a bit of compile-time type-checking thereby. (And I don't say
this lightly: I'm a big fan of compile-time checking.)