Wednesday, January 27, 2010

Wrestling with C

I am by no means a critic of the C language. I think of it as portable assembler. If you need fine-grained control of every machine cycle, you use C. If not, you don't.  It's inappropriate for just about anything else.

However, if you have control over everything the machine does, you have to tell the machine to do things that would happen automatically in other languages. Initializing integers to zero instead of whatever is laying around in memory. This caused a surprising problem in my advanced graphics class today.

The professor has a library of matrix manipulation routines designed for translating, rotating, and scaling objects in three dimensions. He used them for a sample program with two dimensional graphics. However, sometimes the graphic would have a bunch of points at the corner of the window, even though it was supposed to be in the middle. What he eventually figured out was that he hadn't initialized the array that contained the z-coordinates. He assumed, quite reasonably, that since he was working in 2 dimensions, the z-coordinates would be irrelevant. The problem occurred if there was a NaN (not a number) somewhere in the memory allocated for the z array. The NaN would propagate through the matrix multiplication, turning all the coordinates into NaNs.

I have a healthy respect for C, but I can't deny that it causes all manner of headaches.

No comments:

Post a Comment