This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Suggestion for a new warning




J. Kean Johnston wrote:

> Hello again.
>
> Recently I have had cause to argue the following code with several
> people:
>
> char array[256],*p;
> p = some_arbitrary_string;
> while (*p)
>   *p++ = array[*p];  /* THIS IS THE LINE THAT IS BAD */
>
> Syntactically, this is correct. If you know your precedence rules well
> enough it may even be obvious. But it is still (IMHO) very bad code, and
> most people seem to agree.

Never mind the precedence rules. The result of

     '*p++ = array[*p]

is undefined according to ANSI C, because it depends on the order of evaluation
of the operands to =. I agree that warning about such constructs would be nice,
but then you'd have to warn about a zillion other undefined constructs, which
is, in practice, impossible. Consider the following: suppose that, instead of
the above, you write

     char* foo (char** p) { /*...*/ }
     /* ... */
     *foo(&p) = array[*p];

the result is defined iff foo doesn't change p; but the compiler would have to
do a global analysis to make sure, or would have to notice that foo's parameter
is not declared const and warn about _that_ (and, if it were const, hope that
the smart-aleck implementer of foo didn't cast away the const...).

I'd rather not have the compiler warn about undefined behaviour, than to have
it warn only in the most trivial and very obvious cases.

Sorry if I've gone a bit off topic.

    Brane
--
Branko Cibej   <branko.cibej@hermes.si>
HERMES SoftLab, Litijska 51, 1000 Ljubljana, Slovenia
phone: (++386 61) 186 53 49  fax: (++386 61) 186 52 70




Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]