Re: When are unnecessary casts useful?



David T. Ashley wrote:
"ais523" <ais523@xxxxxxxxxx> wrote in message news:1168424781.385448.300330@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
%cat -n test.c
1 int main(void)
2 {
3 char c='c';
4 char* a;
5 a=&c;
6 if(!a || *a > 10) c++;
7 if((!a) || (*a > 10)) c++;
8 if(*a = 10) c++;
9 if((*a = 10)) c++;
10 return 0;
11 }
%gcc -W -Wall test.c
test.c: In function `main':
test.c:8: warning: suggest parentheses around assignment used as truth
value

Note that my version of gcc hasn't warned on line 9; it takes the extra
parentheses as an instruction to suppress the warning. So excess
parenthesisation of this sort can have an effect on compiler
diagnostics, even if it doesn't affect the behaviour of the code.
[..]

But that the extra parens suppress it really surprises me.

The text of the diagnostic message clearly suggests adding brackets to assignments used as truth values. There must be a reason for doing so -- perhaps as mundane as simply to suppress the warning.

Maybe the rationale was if you parenthesize it you are saying "Yo, compiler, I do understand that this assignment has a value, and I want the value of it".

Yes, exactly.

Or (although I doubt it), it could be bug in the compiler.

No. It's by design.

Unfortunately not all compilers take the hint when you just add brackets -- some will continue to warn you. So I've taken to adding both brackets and != 0 to the end:

if((x = y) != 0)

This is pretty warning-proof.

--
Simon.
.



Relevant Pages

  • Re: help: gcc compilation difference
    ... When I compiled the above program with the command " gcc poitr.c" the ... thrown below warning messages. ... array subscript has type 'char' ... C requires all standardised members of the basic execution character set to have non-negative code points. ...
    (comp.lang.c)
  • Re: char as array index gives warning in gcc
    ... char arr; ... Is the gcc warning in any way useful in diagnosing a possible error? ... If you do not want GCC to complain about this, ... I did check the gcc documentation and there was no command line option to suppress this warning. ...
    (comp.lang.c)
  • Re: Warning about constness (I think)
    ... gcc is displaying a warning that confuses me. ... const char** f ... a is of type const A* ...
    (comp.lang.c)
  • Re: Warning about constness (I think)
    ... gcc is displaying a warning that confuses me. ... const char** f ... The return type is const ...
    (comp.lang.c)
  • xemacs installation problems
    ... checking for gcc... ... checking whether we are using GNU C... ... checking size of int... ... configure: warning: No OffiX without generic Drag'n'Drop support ...
    (comp.os.linux.misc)