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!This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
void printStack(char stack[],int *size) { int i; for(i = 0;i <= *size;++i); { printf("Stack Elements %d %c\n",i,stack[i]); } }
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.)
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