Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!cs.utexas.edu!uunet!mcsun!ukc!inmos!conor@lion.inmos.co.uk From: conor@lion.inmos.co.uk (Conor O'Neill) Newsgroups: comp.lang.c Subject: Re: When do you use "if ( a = b )"? (was Re: Funny mistake) Message-ID: <15053@ganymede.inmos.co.uk> Date: 25 Mar 91 11:52:23 GMT References: <8148@rsiatl.Dixie.Com> <15481@smoke.brl.mil> <775@camco.Celestial.COM> <65837@eerie.acsu.Buffalo.EDU> <1991Mar18.195351.11985@unlv.edu> <11109@dog.ee.lbl.gov> Sender: news@inmos.co.uk Reply-To: conor@inmos.co.uk (Conor O'Neill) Organization: INMOS Limited, Bristol, UK. Lines: 46 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@inmos.co.uk US: conor@inmos.com "It's state-of-the-art" "But it doesn't work!" "That is the state-of-the-art".