If-Else If

I never really thought about if statements until sometime last year, when I noticed that an if statement only has an else, there is no such thing as an else if.

I was writing an if statement at the weekend and I was writing an else for that got me thinking about it again.

Another revelation is that Alex from Clockwork Orange is also Caligula from Caligula, and Linderman from Heroes.

if( value == true )
	doSomething();
else if( anotherValue == true )
	doSomethingElseIf();
else
	doSomethingElse();

Take this for example, break up the else if, shifting the if onto a new line and indent, the nature of the if statement is revealed.

if( value == true )
	doSomething();
else
	if( anotherValue == true )
		doSomethingElseIf();
	else
		doSomethingElse();

An if statement only uses the single statement after the if and then the single statement after the else, so the else if is only an else with another if as its single statement.

The way we are allowed to perform multiple statements is to either wrap it in a function, or to use brackets to give scope.

if( value == true )
{
	doSomething();
	doSomething2();
}
else
	if( anotherValue == true )
		doSomethingElseIf();
	else
	{
		doSomethingElse();
		doSomethingElse2();
	}

Of course rather than just indenting, its easier to read with the else and if treated as else if.

if( value == true )
{
	doSomething();
	doSomething2();
}
else if( anotherValue == true )
	doSomethingElseIf();
else
{
	doSomethingElse();
	doSomethingElse2();
}

This can be applied to other statements too, such as for loops, do while loops, and while loops.

// Else-For
if( value == true )
{
	doSomething();
}
else for( int i = 0; i < 2; ++i )
{
	doSomethingFor( i );
}
 
// Else-Do
if( value == true )
{
	doSomething();
}
else do
{
	anotherValue = doSomethingDo();
} while( anotherValue );
 
// Else-While
if( value == true )
{
	doSomething();
}
else while( anotherValue )
{
	anotherValue = doSomethingWhile();
}