Chapter Summary
To make decisions and execute different paths in our programs, we use boolean expressions along with control blocks:
- if: is the simplest way to check whether a condition is met. If the expression is true, the associated block of code is executed.
- if / else: we add an alternative block with else, which will run only if the if condition is not met. This means that at least one of the two blocks will be executed.
- if / else if / else: here we combine multiple different conditions, where only one block will be executed: the first one whose condition is true.
We can also return values and assign them to a constant or variable directly from one of these blocks, as long as we don’t use {} braces to delimit them.
- Labeled blocks: we create labeled blocks using a “label” followed by a colon ( label_name: ) before an opening brace. From inside the block, we can use break :label_name followed by the value to return a result.
- Switch: allows us to evaluate a variable (or constant) against different values. It’s made up of multiple branches, each associated with its own block of code. A block will only execute if the evaluated variable matches its associated value.
Switch can also return a value or execute code, similar to an if.