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

Blair P. Houghton bhoughto at hopi.intel.com
Wed Mar 27 15:07:07 AEST 1991


In article <15053 at ganymede.inmos.co.uk> conor at inmos.co.uk (Conor O'Neill) writes:
>To me it is clear that using assignments inside conditions is very bad
>style because it makes the intention of the original programmer unclear.

No, it's bad because it's an unnecessary obfuscation.  No compiler
in the world won't make
	a=b
	if(a)
the same as
	if(a=b)
as far as any user can tell (provided codocil 4 of para 16 of the
charter of the League of Nations is followed and you didn't
declare a as volatile or apply the -g flag...)

>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

Well, the one I always fret over is

	if ( rindex(path,'/') )
	    /* dammit; another pathname */
	    strcat(newpath, 1+rindex(path,'/'));
	else
	    /* bitchin'; just a filename */
	    strcat(newpath, path);

Yeah, I can declare another variable, but golly, bytes are soooo expensive...

(No strrchr-flames, please; I don't do this where I have
an ANSI library).

>     5    if (a)            b = 99;
>     7    if (a != 0)       b = 99;
>     8    if (a = b)        b = 99; /* This is the confusing one */
>     9    if ((a = b) != 0) b = 99;
>lion/test(49)% icc c.c
>Warning-icc-c.c(8)- use of '=' in condition context
>lion/test(50)%

Nice stuff.  Did you try

	if ( (a==b) != 0 )

and get a redundancy error?

				--Blair
				  "Some of us are redundant.
				   Others merely overloaded."



More information about the Comp.lang.c mailing list