When do you use "if ( a = b )"? (was Re: Funny mistake)

Conor O'Neill conor at lion.inmos.co.uk
Mon Mar 25 21:52:23 AEST 1991


To me it is clear that using assignments inside conditions is very bad
style because it makes the intention of the original programmer unclear.

The only sort of situation which I can think of where I _might_ consider
using it is something like the following:

if ( (x != 0) && ((a = expensive_function(x)) != 0) )
  {
    ...  do something involving 'a'
  }
else if ...  more complicated tests

This example cannot simply move the assignment to 'a' _out of_ the 'if',
because it is conditional on another condition, which may in itself be
complicated. The assignment cannot be moved _into_ the 'if', because
that would change the behaviour of the 'else' clauses.

Of course, there are a multiplicity of ways in which this small example
can be re-written so that the assignment is not inside the condition,
and most of them are probably clearer to read. I would use an alternative.

PS - The INMOS ANSI C compiler produces identical code for the following,
and warns about one of them:

lion/test(48)% cat -n c.c
     1  int main(void)
     2  {
     3    int a, b ;
     4    a = b;
     5    if (a)            b = 99;
     6    a = b;
     7    if (a != 0)       b = 99;
     8    if (a = b)        b = 99; /* This is the confusing one */
     9    if ((a = b) != 0) b = 99;
    10    return 99;
    11  }
lion/test(49)% icc c.c
Warning-icc-c.c(8)- use of '=' in condition context
lion/test(50)%

This warning can be suppressed by a command line switch.

---
Conor O'Neill, Software Group, INMOS Ltd., UK.
UK: conor at inmos.co.uk		US: conor at inmos.com
"It's state-of-the-art" "But it doesn't work!" "That is the state-of-the-art".



More information about the Comp.lang.c mailing list