if

Gamma: Version 4.0
Prev |  | Next

# `if`

`if` -- conditionally evaluates statements.

## Syntax

    if (condition) statement [else statement]

## Arguments

`condition`

  A Gamma or Lisp expression to test.

`statement`

  A statement to perform if the condition is non-nil.

## Returns

The evaluation of the `statement` that corresponds to the satisfied `condition`.

## Description

The `if` statement evaluates its `condition` and tests the result. If the result is non-nil, then the `statement` is evaluated and the result returned.

The `else` option allows for another statement. If the `condition` is nil, the `else` statement (if included) is evaluated and the result returned. This statement could be another `if` statement with another condition and `else` statement, etc., permitting multiple `else/if` constructs. The entire `else` option can be omitted if desired.

| If the `condition` is nil and no else `statement` exists, nil is returned. The `else` part of a nested `if` statement will always be associated with the closest `if` statement when ambiguity exists. Ambiguity can be avoided by explicitly defining code blocks (using curly brackets). In interactive mode Gamma has to read two tokens (`if` and `else`) before it will process the statement. If you are not using an `else` part, you have to enter a second semicolon (;) to indicate that the `if` statement is ready for processing.

## Example

        Gamma> x = 5;
        5
        Gamma> y = 6;
        6
        Gamma> if (x > y) princ("greater\n"); else princ("not greater\n");
        not greater
        t
        Gamma>

The following code:

        name = "John";
        age = 35;

        if ((name == "Hank") || (name == "Sue"))
        {
            princ("Hi ", name,"\n");
        }
        else if ((name == "John") && (age < 20))
        {
            princ("Hi ", name," Junior\n");
        }
        else if ((name == "John") && (age >= 20))
        {
            princ("Hi ", name," Senior\n");
        }
        else
        {
            princ("I don't know you\n");
        }

Will produce the following results:

        Hi John Senior

See the introduction or the Monitor Window section of the Photon Functions chapter (Tutorial One), or the Starting Programs section of the Common Functions for Any Program chapter (Tutorial Two) in the Cogent Tools Demo and Tutorials book for examples of this function used in context.

## See Also

Statements, `for`, `while`

Prev | Home | Next
`function` | Up | `local`

Copyright 1995-2002 by Cogent Real-Time Systems, Inc.