Main Index : Reference :

if - else


Description

Executes different code based on the value of an expression.

Usage

if (expression) 
  doStuff();
if (expression) 
  doStuff();
else 
  doSomethingElse();
if (expression) 
  doStuff();
else if (expression)
  doOtherStuff();
else
  doSomethingElse();

Program Structure

With if and else one can branch one's code based on the value of expression. When expression is either 0 or nil it is said to be false. Any other value means that expression is true. The code that follows an if statement is only executed if expression is true.

An if statement can be followed by an else statement. The code that follows an else statement is only executed if the preceeding if statement's expression is false.

An else statement can also be conditional, if one adds an if statement to it. The code that follows an else if statement is only executed if expression is true and the preceeding if statement's expression and all the preceeding else if statements' expressions are false.

If the code to be executed is on several lines, it must be enclosed in braces, {}.

The expression often consists of comparison operators, such as ==, !=, >, >=, < and <=. These can in turn be combined with logical operators, such as &&, ! and ||. You can read more about these operators here.

Example

// Assigns a value of 3 to x.

var x = 3;


// Nothing is done since x is not equal to 10.

if (x==10) println("x is 10");


// The code block is exectuted since x is less 
// than 5. (x will have the value 6 afterwards)

if (x<5)
{
  x = x*2;
}


// The else code is executed since the if expression
// (x is not 3) was false.  (x will be 1 afterwards)

if (x!=3)
  x = x-3;
else
  x = 1;
  
  
// Nothing is done since both the if expression and
// the else if expression were false.

if (x==4)
{
  x = x+2;
  println("x was 4");
}
else if (x==5)
  println("x is 5");
  
  
// The second else if code is executed since all earlier
// expressions were false. (x will be 2 afterwards)

if (x==10)
  x = 9;
else if (x==8)
  x = 5;
else if (x==3)
  x = 2;
else
  x = 0;
  
  
// An example of logical operators. The code will be
// executed if x is between 1 and 7.

if (x>=1 && x<=7) doStuff(x);

See Also

Operators