What is flow control and the exit statement in Euphoria?
What is flow control?
Flow control is the process of breaking the default order of a program statement’s execution. The default behavior of a program’s execution flow is to automatically run the next program after the current one. Flow control, however, allows us to set up a custom execution order for any execution block in our code.
The Euphoria language provides simple program structures or statements for flow control, such as exit, break, continue, retry, with entry, and goto.
This shot focuses on the exit statement.
What is the exit statement?
The exit statement causes the flow of a program to immediately terminate the loop, and continues the program execution with the first statement after the end of the loop.
Wherever the exit statement is placed in a loop during program execution, the loop exits, and the normal code flow recommences.
Code
The code below contains a loop that exits at some point if the condition is met.
Note: We need to include the
std/math.efile in our program.
include std/math.eatom x = 2, y = 10, z = 5for i = x to y doif z = i thenprintf(1,"this works \n")exit -- if true stop executing code inside the 'for' block.if z < y thenprintf(1,"does not")end ifend ifend for-- Flow restarts here.if z > x thenprintf(1,"\n The execution flow has recommenced")end if
Explanation
The for block will exit if the first if condition returns true. This means that the code contained in the second if block will not run. Instead, we execute the rest of the program below the for loop.
- Line 1: We include the
std/math.efile. - Line 3: We declare variables and assign values.
- Line 4: We start the
forloop that extends until line 16. - Lines 6 to 13: This contains some
ifstatements that are the codes to be executed when theforloop runs. - Line 9: This is where the
exitstatement is used to exit the program when theifcondition on line 6 evaluates totrue. - Line 10: The
ifcondition on this line executes if theexitstatement is not stated right above it. - Line 19: The normal flow of execution in the program recommences, after the
forloop exits on line 18. Anifloop starts, and it ends on line 21.