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

Checkpoint Technologies ckp at grebyn.com
Mon Mar 18 03:53:14 AEST 1991


In article <65837 at eerie.acsu.Buffalo.EDU> chu at acsu.buffalo.edu (john c chu) writes:
>In article <775 at camco.Celestial.COM> bill at camco.Celestial.COM (Bill Campbell) writes:
>[concerning "if ( a = b )"
>>Certainly it
>>is a legal construction, but 90% of the time when I do this it
>>was my mistake!
>
>It's been my mistake everytime I've done it!! I realize that it is a
>legal construction and I know what it does, but I was wondering...
>Is there a good use for this?

No.  More specifically, as long as it's really a simple assignment with
no side effects, it's out.

You *can* do this, and some might say it's a "valid" use:

b = function(args);
if(a = b) { ...

Some programmer might have really meant it this way, to test the result
from the function call for zero.  But if I were writing it (and I
hazard to guess most everyone else reading this would agree, at least in
principle) it would appear this way:

a = b = function(args);
if(a) { ..  /* or else if(b) */

I have seen the following code examples frequently, and I consider them
valid:

if(code = setjmp(jmploc)) { ...

 - and -

if(pid = fork()) { ...

The reason they are valid is because the expression contains a
significant side effect.
-- 
First comes the logo: C H E C K P O I N T  T E C H N O L O G I E S      / /  
                                                ckp at grebyn.com      \\ / /    
Then, the disclaimer:  All expressed opinions are, indeed, opinions. \  / o
Now for the witty part:    I'm pink, therefore, I'm spam!             \/



More information about the Comp.lang.c mailing list