Saturday, June 13, 2009

Oh, those pesky semi-colons!

I have a great fascination on the origin of things, whether it is the current set of books I am reading about early American history1, or the various nostalgic videos on the beginnings of Microsoft, or even the posts by Andy Hertzfield on the early beginnings of the Mac. C is a language that has that same nostalgic appeal to me as well. It's the pre-pre cursor to C#, the language I actually get paid to write in. In life's continual twists, I am now on a team that has some applications that interface with C and C api's. Most people I mention this to reply, "ugh.. you have to learn C?!?!?" But to me, it's something to learn and since C is the predecessor to C#, it scratches my itch for learning about the origin of things.
On a recent trip to my local public library there is a shelf for free books, and to my amazement, there was a copy of Problem Solving & Program Design in C. Sarcasm aside, I couldn't understand why it was still there for my taking. In the chapter on arrays, there is a simple program on writing a stack, I added a print function to this program to list all the elements.
This code compiles, but when I ran it, I only saw the last element in the array. Hmmm...strange. I fooled around a little adding some extra printlines, check some other code snippets and I can't find what is going on!
Eventually, after a day or so, what was wrong was I had a semi-colon at the end of my for loop declaration. The C compiler accepted this code as valid code and when my program ran, the for loop looped over itself, never proceeding into my brackets until i <= *size was actually true, then only printed the 3rd element in my array!
To me, there are several thoughts I took away from this little problem.
  • What a great lesson to enforce really reading your code before you execute.
  • An increased appreciation for the C# compiler to not let me even make that mistake in C#. (The compiler gives you a warning.)
I would love to see what comments, if any, others have on the merits of learning C, really learning C, when your primary programming language is C#. Personally, I see merits in knowing/learning this language if not for the only habit to slow down and really read my code.

1If your looking to get a nice start on early American History, I suggest the following:
  • John Adams by David McCullough
  • 1776 by David McCullough
  • Benjamn Franklin by Walter Isaacson
  • Founding Brothers by Joseph Ellis
These authors have written several additional books, but these are great primers on the subject.