kmote
Seg Fault'n,
- Messages
- 5,801
Inspired by this post: http://www.techist.com/forums/1654284-post12.html, I thought it might be good to have a thread explaining some of the general programming errors that sneak into code all the time. Hopefully over time this will form a nice descriptive list which will help people avoid and, if necessary, detect them. Post up ones you have made, seen or think could easily happen a bit like this (witty names are non-optional lol):
Is it equal then?
Example:
Fairly simple, you put it in an if statement so you expect it to check aNumber is 1 before printing. Unfortunately = is the assignment operator meaning that aNumber is set to 1 then evaluated to provide the answer for the if, result... it will always print. And don't think you're safe from this by using a language such as java which only accepts a boolean answer to if because the exact same thing applies. This one can be caught at compile time (as a warning) in some languages such as c but others are more of a problem.
The "nevermind" conditional
Example:
You don't expect Hello world to be printed but guess what... your program has a surprise for you and it's all because of the sneaky semicolon after the if. This particular error is nasty because it doesn't show at compile time and may not show for most of the runtime. If you expect iWantToPrint to be true most of the time, you won't be surprised when it does print and on the odd occasion iWantToPrint is false the outcome way be more subtle than a print statement.
The moving goalposts
Example:
It seems so simple here because the difficulty of this one lies in the complexity of the code inside the loop so as soon as it is put into a nice simple example it seems obvious. The general idea though is that the programmer has inadvertantly created an infinite loop by continually moving the target that would otherwise break it.
The leaky case
Example:
Again completely legal, this is actually a powerful and useful feature of switch that allows one case to "flow" into another - that's the best way I can describe it without saying that the above code runs doSomething(), doSomethingElse() and orThis() and that if aVar was 2 it would run doSomethingElse() and orThis(). Only problem is that it is easy to do accidentally and it is a matter of the programmers disipline to put a break before the next case if you don't want this.
Is it equal then?
Example:
Code:
int aNumber = 0;
if (aNumber = 1)
{[indent]printFunction("You don't want this to print");[/indent]}
The "nevermind" conditional
Example:
Code:
boolean iWantToPrint = false;
if (iWantToPrint);
{[indent]printFunction("Hello world");[/indent]}
The moving goalposts
Example:
Code:
int current =0;
int top = 1;
while (current < top)
{[indent]printFunction(current);
top++;
current++;
pauseExecution(1, SECOND);[/indent]}
The leaky case
Example:
Code:
int aVar = 1;
switch(aVar)
{
case 1:
doSomething();
case 2:
doSomethingElse();
default:
orThis();
}