There is no spoon

If statement

From Unreal Wiki, The Unreal Engine Documentation Site
Revision as of 00:05, 9 February 2009 by Wormbo (Talk | contribs) (added related links to switch and conditional operator)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

The if statement provides a simple way to branch code execution paths based on a condition. When the condition is met, a certain piece of code can be executed and optionally, when the condition is not met, another piece of code can be executed.

Syntax[edit]

The simple if statement looks as follows:

if (condition)
  statement;

The condition is a boolean expression and if it evaluates to True at runtime, the statement is executed.

If more than one code statement should be executed, simply enclose them all in curly braces:

if (condition) {
  ...
}

Additionally, when the condition evaluates to False, a different piece of code can be executed:

if (condition)
  statement;
else
  statement;

Of course, this also works with a block of code:

if (condition) {
  ...
} else {
  ...
}

You can even combine the block and simple forms:

if (condition) {
  ...
}
else
  statement;

...or:

if (condition)
  statement;
else {
  ...
}

To prevent confusion, it may be a good idea to always use curly braces, even if you only put a single statement after the if or else part.

"ElseIf" statement[edit]

The if statement in UnrealScript does not support an "elseif" clause, like e.g. BASIC dialects do. Instead, you can simply add another if clause in the else part:

if (condition1) {
  ...
} else if (condition2) {
  ...
} else if (condition3) {
  ...
} else {
  ...
}

The "dangling else" problem[edit]

Consider the following example code:

if (a)
  if (b)
    doSomething();
else
  doSomethingElse();

This looks highly ambigious. Which if does the else belong to? Indenting would suggest it belongs to the first if statement. However, the compiler ignores all indenting, so the else may as well belong to the second if statement.

Using curly braces, the above code may look as follows:

if (a) {
  if (b) {
    doSomething();
  }
} else {
  doSomethingElse();
}

Or like this:

if (a) {
  if (b) {
    doSomething();
  } else {
    doSomethingElse();
  }
}

Obviously these two implementations are not the same, but which one would be used if you left out the curly braces?

This problem is called "dangling else" and the compiler solves it by applying a simple rule: An else statement always belongs to the inner-most preceeding if statement. In our case, this is the "if (b) statement".

Related concepts[edit]