GOOC - Game Oriented Object C

GOOC - Game Oriented Object C

Next: The while and until Statements, Previous: Blocks, Up: Statements
[Contents]

8.3. The if and unless Statements

8.3. The if and unless Statements

You can use the if or unless statements to conditionally execute part of your program, based on the truth value of a given expression. Here is the general form of an if statement: if (test) then-statement else else-statement If test evaluates to true, then then-statement is executed and else-statement is not. If test evaluates to false, then else-statement is executed and then-statement is not. The else clause is optional. If unless is used instead of if, then the truth value of test is flipped. Now, then-statement is executed if test is false, and so on.

You can use a series of if and/or unless statements to test for multiple conditions: if (x == 1) y = 10; else if (x == 2) y = 20; else unless (x == 4) y = 30; else y = 50;

You can also optionally define variables within the condition. This is useful if you want to compare an expression which does not have a consistent return value, such as rand. The scope of this variable lasts until the if (or unless) statement chain it was declared in is over. /* rand(3) returns a random value from 0 to 2, and we run different code depending on each of the three outcomes */ if (var r = rand(3); r == 0) y = 10; else if (r == 1) y = 20; else if (r == 2) y = 40; x = r // error