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: suggest parentheses around assignment used as truth value


"Brad M. Garcia" <bgarcia@fore.com> writes:

 > > I'd just like to register my opiniont that code like
 > > 
 > > if (x = p()) {...}
 > > 
 > > shouldn't generate a warning under gcc -Wall.  Even if
 > > you feel that code like this is obscure, the recommended
 > > 
 > > if ((x = p())) {...}
 > > 
 > > is just bizarre.
 > 
 > In 80% (don't you love making up statistics?) of cases where "=" is
 > used inside an "if" expression, the programmer meant to use "==".  So
 > the warning is helpful.

I believe the original poster might be making a distinction btw

   if (x = p()) ...

and

   if (x = y) ...

The second case (where the lvalue and rvalue are variables) is the one
where comparison is typically meant instead of assignment, and which
the gcc warning should apply to.

In the first case (where the rvalue is a function call) it's not at
all clear to me that comparison

   if (x == p()) ...

is more common than assignment

   if (x = p()) ...

or even that assignment is a common mistake when the programmer means
comparison.

There are bad things about both constructs.  The first is doing a
comparision inside the if test instead of an assignment, but is also
losing the return value of the function.  The second is keeping the
return value, which is a good thing, but at the cost of doing an
assignment inside of the if test.

It's not clear that gcc should value one over the other.

Maybe there should be a different independently settable warning for
the case where the rvalue is a function return?

-- 
Harvey J. Stein
BFM Financial Research
hjstein@bfr.co.il


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