This post originated from an RSS feed registered with .NET Buzz
by Doug Thews.
Original Post: Make 2=0 In Your Code
Feed Title: IlluminatiLand
Feed URL: http://apps5.oingo.com/apps/domainpark/domainpark.cgi?client=netw8744&s=JETBRAINS.COM
Feed Description: A technology blog for people enlightened enough to think for themselves
I was digging through some old code the other day and found a compiler for a mythical testing language I wrote several years back. I noticed a comment that brought some memories back. It said: "Don't let 2=0". Let me explain.
In college, I was having trouble with one of my programs getting a Divide By Zero error. I was sure that the denominator in the equation wasn't zero, so I did the old print to find out what was wrong (this was in the Pascal days). Anyway, to my surprise, the denominator was zero. So, more screen prints to find out which variable was causing the problem. I debugged it down to this equation (simplified for example purposes)
print (2*x);
print (x);
Guess what, I got zero and 1000! Being totally confused, I did the following:
print (2);
To my surprise I got 0!
How did this happen? Well, investigation with the professor found a routing of mine that caused the problem. I used a routing that passed in a value by reference.
MyRoutine (int y);
In MyRoutine, I had a loop that needed to be run, so I did:
while y >0 =0
(
y = y -1;
}
Then, I called the routine like this:
MyRoutine(2);
What happened in the old Pascal (and Fortran, too) was that the compiler creates a variable called "2" and assigns a value of 2 to it. When I passed in "2" by reference, the compiler didn't care and passed the pointer to the "supposed" constant. My loop then decremented "2" until the value of the constant equals 0!
I've tried this trick when testing new compiler versions, macros, languages (even test tools), and anything else that supports routines and passing by reference. Now, most of today's enterprise languages are smart enough to keep constants just that. But, every once in a while you'll run into a freeware scripting tool or something else that fails this little test.
Next time you get a new tool. Give it a try. Better yet, pull out that old copy of the original Turbo Pascal and try it yourself.