Wednesday, July 8, 2009

Semicolon after the if statement

Too frequent mistake to stay quiet about : the semicolon ";" after the if statement

consider the code

if (booleanMethod(s1,s2));
{
return true; // will be executed anyway
}

The code will return true in every case , because there is a semicolon after the if statement. The problem lays in the definition of the semicolon in modern languages such as C# and JAVA semicolon defines the ending of the statement and since the If statement doen't have to be followed by any other statement the true meaning of the upper code is :
if booleanMethod is true
do - nothing;
return true;

so if we want the code to return true only if booleanMethod is true the correct form would be without the semicolon after the if

if (booleanMethod(s1,s2))
{
// only if the if is true
return true;
}

No comments:

Post a Comment