Testing for TRUE and FALSE; A Problem Scenario

I wish they did better fact checking in these textbooks. Here’s a case in the C Programming book I’m reading. I was having problems with the following code:

FILE* spIn;
spIn = fopen("program73.dat", "r");
if(spIn != NULL)
 {
 printf("Could not open file.\a\n");
 exit(101);
 } // if open fails

Here’s the problem. The line if(spIn != NULL) always exits the program. However, if(!spIn) and if(spIn == NULL) both work fine.

The problem is that he was telling the program to terminate if the file opened successfully, the opposite of what he meant. The file pointer returns NULL if it’s not able to open the file. He told the program to exit if the pointer did not return NULL; in other words, the program terminated every time the file opened successfully. The other two checks I used checked to see if NULL was returned and the program would exit only if the file did not open successfully.

In a textbook, I certainly think the author should compile and test his programs to see if they work correctly a greater extent than this. However, this underscores a common problem for programmers. It’s very easy to get your tests backwards when testing for true and false conditions.

The best rule? Keep it simple and readable. If you have to take time to think through the logic, look for an easier way to write the condition. The second best rule, I guess, is to actually compile and run a program before you include it in a book, just to make sure it works correctly.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s