Re: When are unnecessary casts useful?



"David T. Ashley" wrote:
"ais523" <ais523@xxxxxxxxxx> wrote in message

%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.

The behavior you illustrated is unexpected. What a surprise!

We all know that one of the most frequent human errors (at least,
until you've used 'C' for a long time) is to write something like:

if (x=0)

when you really mean

if (x==0)

so I'm not surprised that the compiler will flag that.

But that the extra parens suppress it really surprises me.

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".

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

No bug. in "if (x = 0) {" the tested item is an assignment
statement, which incidentally also yields a value. In "if ((x =
0)) {" the tested statement is a parenthized expression, which
intrincically has a value, and the compiler can tell what is going
on. Of course the sane thing to do is to write those as "if (0 =
x)", assuming you want to test against 0 and avoid failing to flag
the erroneous assignment statement.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>


.



Relevant Pages