Selection control structures are programming constructs that allow you to make decisions and execute different code blocks based on specific conditions. They play a crucial role in controlling the flow of execution in your Carbon programs.
if
Statement
The if
statement is the most basic selection control structure. It executes a block of code only if a specified condition is true.
Code snippet
var age: int = 25;
if age >= 18 {
print("You are an adult.");
}
else
Statement
The else
statement can be combined with the if
statement to provide an alternative block of code to execute if the condition in the if
statement is false.
Code snippet
var age: int = 25;
if age >= 18 {
print("You are an adult.");
} else {
print("You are a minor.");
}
else if
Statement
The else if
statement allows you to check additional conditions if the previous if
or else if
conditions are false.
Code snippet
var grade: int = 85;
if grade >= 90 {
print("Excellent!");
} else if grade >= 80 {
print("Good job!");
} else {
print("Needs improvement.");
}
switch
Statement
The switch
statement is a more concise way to handle multiple conditions. It compares a value against a set of cases and executes the corresponding code block.
Code snippet
var day: string = "Monday";
switch day {
case "Monday":
print("It's Monday!")
case "Tuesday":
print("It's Tuesday!")
default:
print("It's another day!")
}
Nested Conditional Statements
You can nest conditional statements within each other to create more complex decision-making logic.
Code snippet
var age: int = 20;
var isStudent: bool = true;
if age >= 18 {
if isStudent {
print("You are an adult student.");
} else {
print("You are an adult non-student.");
}
} else {
print("You are a minor.");
}
Conditional Expressions
Carbon also supports conditional expressions, which allow you to evaluate a condition and return a value based on the result.
Code snippet
var message: string = age >= 18 ? "You are an adult." : "You are a minor.";
Selection control structures are essential for writing flexible and efficient Carbon programs. By understanding and using them effectively, you can create complex decision-making logic and control the flow of execution in your code.