-
Notifications
You must be signed in to change notification settings - Fork 0
Control Flow
soup has a couple of constructs allowing the user to execute certain instructions based on the value of a boolean expression.
if [expression] {
...
}
The if
construct allows for the execution of a collection of instructions only if a boolean expression evaluates to true
.
Example 1:
printf("Before if\n");
if true {
printf("Inside if\n");
}
printf("After if\n");
Output:
Before if
Inside if
After if
Example 2:
printf("Before if\n");
if 1 == 2 {
printf("Inside if\n");
}
printf("After if\n");
Output:
Before if
After if
if [expression] {
...
} else {
...
}
The if-else
construct allows for the execution of a collection of instructions only if a boolean expression evaluates to true
, and a separate collection of instructions only if it evaluates to false
.
Example 1:
printf("Before if-else\n");
if 99 < 100 {
printf("Inside if\n");
} else {
printf("Inside else\n");
}
printf("After if-else\n");
Output:
Before if-else
Inside if
After if-else
Example 2:
printf("Before if-else\n");
if (2 <= 3) && (5 == 6) {
printf("Inside if\n");
} else {
printf("Inside else\n");
}
printf("After if-else\n");
Output:
Before if-else
Inside else
After if-else
while [expression] {
...
}
The while
loop allows for the execution of a collection of instructions repeatedly as long as a boolean expression evaluates to true
.
Example:
int x = 1;
while x <= 5 {
printf("x = {}\n", x);
x += 1;
}
Output:
x = 1
x = 2
x = 3
x = 4
x = 5
An oft-forgotten aspect of writing while loops is the crucial updating of the condition that keeps the while
loop looping. Consider the same example, but with the easily forgettable x += 1
line omitted:
int x = 1;
while x <= 5 {
printf("x = {}\n", x);
}
Output:
x = 1
x = 1
x = 1
x = 1
x = 1
x = 1
x = 1
...
Since we are no longer updating the value of x
, it will always be 1
, the expression x <= 5
will never become false
, and therefore the loop never exits.