Conditionals
A conditional statement is programming construct that executes different code depending on whether a given condition is true or false. In Cambo, there are 3 main statements built into the language:
- if statement (if, if else, else if).
- match statement.
- expression-based statement.
If statement
An if statement is control strucuture that executes a line or a block of code when a specified condition evaluates to true.
if
if(condition){
# code...
}
Example:
int age = 18;
if(age == 18){
print("you are 18.");
}
In the code above, you are 18. will be shown because the condition
age == 18 is true.
if else
if(condition){
# code ...
} else {
# code ...
}
Example:
int age = 15;
if(age >= 18){
print("you're eligible.");
} else {
print("you're not eligible.");
}
In this case age is assigned to be 15, so you're not eligible. will be printed into the terminal.
else if
In some cases, you may need to check more conditions, not just only one or two. Therefore, there's a way to do that, which is the else if statement.
if(condition){
# code ...
} else if(condition){
# code ...
} else {
# fall back code...
}
else if as many times as you want, however too many of them is not recommended.Example:
if(age > 18){
print("you're over 18.");
} else if(age < 18){
print("you're below 18.");
} else {
print("you're 18.");
}
Here we can check if age is above or below 18. Also, you can clearly see that we don't need to check if age is 18 or not, the else takes care of this for us already.
else if is actually better than if, if, if and so on, because else if stops evaluating as soon as it finds a true condition.Match statement
"A match is a conditional statement that evaluates an expression, compares the result against multiple case values, and executes the corresponding block of code for the first match found."
match(expression){
case value:
# code ...
break;
case value:
# code ...
case value:
# code ...
break
otherwise:
# fall back code ...
break
}
Example:
# assume `day` is a variable of string type
match(day){
case "mon":
print("today is monday.");
break;
case "tue":
print("today is tuesday.");
break;
case "wed":
print("today is wednesday.");
break;
case "thu":
print("today is thurday.");
break;
case "fri":
print("today is friday.");
break;
case "sat":
print("today is saturday.");
break;
case "sun":
print("today is sunday.");
break;
}
If you have one same block of code for multiple cases, you can use | to indicate one or more alternatives. For example:
match(day){
case "mon" | "tue" | "wed" | "thu" | "fri":
print("today is a weekday.");
break;
case "sat" | "sun":
print("today is a weekend.");
break;
}
Expression-based statement
comming soon.