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

Kevin Grover grover at sonny-boy.cs.unlv.edu
Tue Mar 19 05:53:51 AEST 1991


In article <65837 at eerie.acsu.Buffalo.EDU>, chu at acsu.buffalo.edu (john c chu) writes:
) From: chu at acsu.buffalo.edu (john c chu)
) Subject: When do you use "if ( a = b )"? (was Re: Funny mistake)
) Date: Sun, 17 Mar 91 04:53:11 PST
) Organization: SUNY Buffalo
) 
) 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?
) 

There are plenty of uses for it.  It will allow smaller code, and checks to be
done quikcer.  I have done it by mistake a time or two, but I find it quickly.
One, of my most common uses is

    if  (  !(fp=fopen("file","r")) )   perror ("Could not open file");

Which is the same (logically) as:

    if  (  (fp=fopen("file","r")) == NULL )   perror ("Could not open file");

This code tries to open the file, if it did not, if prints a message (and aborts)
the program.  You could then put the rest of the code in an else (for clarity)
or simply put it after the if.

Also, if you get bitten but this bug often, try something like

	#define EQU ==

	if ( a EQU b)

Instead of depending upon remembering to use '==' when you need to.


-- 
  +-------------------------------------------------+----------------------+
  | Kevin Grover             UNLV Computer Science  |     Home of the      |
  | grover at cs.unlv.edu       Las Vegas, Nevada      |    Running REBELS    |
  +-------------------------------------------------+----------------------+



More information about the Comp.lang.c mailing list