Sambar Server Documentation

CScript If/then/else


The if/then/else statement is used to decide whether to do something at a special point, or to decide between two courses of action. The simplest form of the if statement is:
if ( expression ) statement
The condition to be tested is any expression enclosed in parentheses. It is followed by a statement. The expression is evaluated, and if its value is non-zero, the statement is executed. The following conditional execution decides whether a value has is greater than the passing mark of 70:
if (result >= 70) printf("Pass\n"); else printf("Fail\n");
If the test evaluates to zero then the statement following the else is obeyed (if there is an else statement present). After this, the rest of the program block is executed as normal. The character sequence `>=' is one of the relational operators in C; here is the complete set:
==equal to
!=not equal to
>greater than
<less than
>=greater than or equal to
<=less than or equal to
The value of ``expression relation expression'' is 1 if the relation is true, and 0 if false. Don't forget that the equality test is `=='; a single `=' causes an assignment, not a test.

Tests can be combined with the operators `&&' (AND), `||' (OR), and `!' (NOT). For example, we can test whether a character is blank or tab or newline with:

if (c == ' ' || c == '\t' || c == '\n') ...

If more than one statement is desired following the if or the else, they should must be grouped together between curly brackets ({ }). Such a grouping is called a compound statement or a block.

if (result >= 70) { printf("Passed\n"); printf("Yahoo!\n") } else if (result <= 30) { printf("Failed\n"); printf("You'll never make it!\n") } else { printf("Failed\n"); printf("Good luck next time.\n"); }

The above statements also demonstrate a multi-way decision based on several conditions using an else if statement. This works by cascading several comparisons. As soon as one of these evalutates to a true result, the following statement or block is executed, and no further comparisons are performed.

Conditional expression

C provides an alternate form of conditional which is often more concise. It is called the conditional expression (or trinary operator) because it is a conditional which actually has a value and can be used anywhere an expression can. The value of:
a < b ? a : b;
is a if a is less than b; it is b otherwise. In general, the form
expr1 ? expr2 : expr3
means: evaluate expr1. If it is not zero, the value of the whole thing is expr2; otherwise the value is expr3. To set x to the minimum of a and b, then:
x = (a < b ? a : b);

© 2001 Sambar Technologies. All rights reserved. Terms of Use.