If statement
In Rell, the if
statement is used to create conditional logic that allows you to execute different blocks of code
based on whether a specified condition is true or false.
if condition {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
condition
: This is the expression that evaluates to either true or false. If the condition is true, the code within
the first block (between {}
) will be executed. If the condition is false, the code within the else
block (also
between {}
) will be executed.
Example:
if (x == 5) print('Hello');
if (y == 10) {
print('Hello');
} else {
print('Bye');
}
if (x == 0) {
return 'Zero';
} else if (x == 1) {
return 'One';
} else {
return 'Many';
}
In this example,
if (x == 5) print('Hello');
This snippet checks if the value of variable x
is equal to 5. If the condition is true, it prints "Hello".
if (y == 10) {
print('Hello');
} else {
print('Bye');
}
In this snippet, if the value of variable y
is equal to 10, it prints "Hello". If the condition is false, it prints
"Bye". This is a correct representation of an if
statement with an else
block.
if (x == 0) {
return 'Zero';
} else if (x == 1) {
return 'One';
} else {
return 'Many';
}
This snippet involves an if-else if-else
chain. If x
is 0, it returns the string "Zero". If x
is 1, it returns the
string "One". If neither of these conditions is met, it returns the string "Many".
You can also use the if
statement as an expression:
function my_abs(x: integer): integer = if (x >= 0) x else -x;