Logic Error?

Posted by on March 9, 2009

I was reviewing some code the other day and I came across an interesting section. The code is written in C#.

public void DoSomething()
{
if( 1 == 1 );
{
// Do Something;
}
}

What might not be immediately obvious is that there is a semi-colon terminating the IF statement. This function will compile. It will give you a warning, but it will not stop you from running the code. When this is run, the block after the if statement will always run. This is because the if statement is terminated and the block is just a valid block of code (often used for scoping variables). If this was logic for access to features, it could be easily overlooked and everyone would have access to the features. Of course, the testers should catch this type of error, but what if they didn’t? There may be a case where you would want to code a statement like this (maybe with a different if clause), but most cases would not want this design. This proves a strong point to glance over the warnings that the compiler throws. I felt this was an interesting code snippet I saw and wanted to share it with anyone else that may come across this one day.

Comments

Comments are closed.