Related Articles

2 users responded in this post

Subscribe to this post comment rss or trackback url
User Gravatar
Stephen said in December 12th, 2007 at 11:09 am

There are 18 entries in this “Top 10″ list. Yet, the blog doesn’t prevent this. In fact, it seems to work, just like C.

User Gravatar
Stephen said in December 12th, 2007 at 11:55 am

In the first edition of the K&R C book (the white book), one of the examples was a handy function called “index”. It took two strings, searched one for the other, and return an integer, which was the offset of the found string, or -1 if not found.

However, the standard C library has a function called “index”. But this one takes a string and a character, and returns a pointer to the found character, or NULL. It’s not the same. The linker sees your definition of index, and uses it, and prunes the one from the standard library – since you already have it defined. This was intentional in the C design. It let you override functions in any library. One might even call this idea object-oriented.

But the trouble was, other bits of the C library, notably the standard I/O stuff, like printf(), used index(), and expected a function that took the string and character, and returned a pointer. So, when you defined the index() function that behaved otherwise, printf() became effectively broken. Very hard to track down, especially back in the adb(1) debugger days.

These days, one would use strstr() to find one string in another. One would use strchr() to find a character in a string. The standard library still has index(), but no longer uses it. And, the compiler complains that you haven’t defined index() if you just use it and haven’t either declared it or included “string.h”. In either case the compiler then matches the definition with your call’s argument types. All this means that this error has been closed. Part of it was the 1987 ISO C (ANSI C), and part of it was a better construction of the standard library and headers.

But some of the Top 18 are addressed with standard approaches. For example, number 8, is solved by simply always using braces. They’re optional, but you can always use them. Since 1988, i’ve always used them. It’s easier to edit the source that way. But some people (not me) omit braces for single line if’s:

if (test) doit();
if (test2) dosomemore();

The problem with these standard approaches is that they probably aren’t written all it one spot, especially where *every* starting C programmer can learn them. C is not for the novice. Trouble is, everyone starts out as a novice.