Log in

No account? Create an account

Previous Entry | Next Entry

The following is a simple C programming language implementation of the Unix cat program, which (among other things), writes what it reads from the standard input to the standard output.

#include <stdio.h>

#define TRUE 1

int main()
        int c;

        while (TRUE) {
                c = getchar();
                if (c == EOF) {

This program is "correct" -- it does what it claims to do. However, there is (at least) one problem with the program that an interviewer might hold against a candidate. It is the "c == EOF" condition. There is a school of thought that says that the arguments should be reversed, because if someone accidentally uses a "=" instead of "==", the program will not work correctly, even though the compiler will not detect any errors. (FYI, EOF is a constant that when encountered in a file stream such as provided with getchar(), indicates that the end of the file has been reached.)

Why is this an issue? Because many reference books, including K&R, the definitive text for the C programming language, is full of examples where <variable> == <constant> is used. Someone who's used K&R for years, and never allowed such a mistake to get into production code, might actually miss out on a job opportunity because not realizing (or knowing about this), plus perhaps a couple of other mistakes made due to nervousness or some other random thing, might make them a less desirable candidate.

Where does one go to find out about such issues? I don't ever remember seeing code implemented in the "safe" way before 1992. When I first saw it, I thought it looked unusual. Possibly, this issue is discussed on the usenet group comp.lang.c, or it may be in another C programming book. But when someone is focusing on this issue, what issues aren't they focusing on that might be critical to getting a job, or doing the job they're hired for? Suppose they aren't protecting their code against fraudsters? What would a customer say, when presented the choice of protection against fraud vs. safeguarding against a mistake that "might happen?"



( 3 comments — Leave a comment )
Sep. 11th, 2007 10:23 pm (UTC)
in modern terms…
Constants, especially negative ones, are defined in parens, e.g.:

#define EOF (-1)

Thus defending against what you brought up.
Sep. 12th, 2007 05:18 am (UTC)
Re: in modern terms…
Hmmm ... Perhaps I didn't explain well. The problem occurs if someone assigns EOF to c, instead of testing for equality. Apparently, this is a common mistake; enough for interviewers to check for it.
Sep. 12th, 2007 07:39 pm (UTC)
Re: in modern terms…

Companies serious about stomping bugs will also use verification tools. Everyone makes mistakes.
( 3 comments — Leave a comment )