Game Development Reference
In-Depth Information
In between those curly braces, we will type the code to be executed if the statement was to
return true. As the statement will return false, any code inside those curly braces will be
skipped, and the program will move on to whatever is next.
The else statement
What if we want to do something else when an
if
statement evaluates as false? For this,
we have what is called the
else
statement. This allows us to do something when it evalu-
ates as true; otherwise (if it does not evaluate as true), do something else.
The
else
statement must be accompanied by an
if
statement to work.
In the following screenshot, you can see how an
else
statement is structured:
As you can see, it is structured fairly similar to the
if
statement itself, the difference be-
ing it doesn't need something to check for it to function. Any code in the curly braces that
follows the
else
statement will be executed if the
if
statement returns false instead of
true. Should the
if
statement return true, then the code for the
else
statement would be
skipped.
The else if statement
What if we want to do something when the
if
statement returns false, but we only want
to do it if something else returns true at the same time?
For this, we have the
else if
statement. If you guessed it being a combination of the
if
and
else
statements, then you are correct. The
else if
statement allows us to do
something when the original
if
statement isn't true and another
if
statement is true.
That may be confusing, so let's look at an actual
else if
statement in use.