Flow of Control (Control Flow)
Control flow refers to the order in which instructions, statements, and function calls are executed in an imperative program. It determines how the program progresses based on different structures.
Types of Control Flow
- Sequential Execution – The program executes statements one by one in order.
- Conditional Execution – The program decides which block of code to execute based on a condition (e.g.,
if/else
in most languages,jne
in assembly). - Loops (Repetition) – The program repeatedly executes a block of code (
for
,while
,do-while
). - Function Calls – Control is transferred to a function and returns when it completes.
- Exception Handling – The program attempts to handle errors using structures like
try/catch/finally
.
Some control flow structures can be combined, such as using while
with break
, continue
, or goto
for finer control.
Imperative vs. Declarative Programming
Imperative Programming
Imperative programming explicitly defines the step-by-step process to achieve a result. The following C++ example demonstrates an imperative approach to summing an array:
#include <vector>
#include <iostream>
int main() {
std::vector<int> v = {1, 2, 2, 3, 3, 1, 2, 2};
int sum = 0; // Initialize sum to avoid undefined behavior
for (size_t i = 0; i < v.size(); i++) {
sum += v[i];
}
std::cout << "Sum: " << sum << std::endl;
return 0;
}
Here, we explicitly define how to iterate through the array and sum its elements.
Declarative Programming
Declarative programming focuses on specifying what the result should be rather than how to achieve it. The system takes care of the implementation details.
Example in C++ using std::accumulate
:
#include <vector>
#include <numeric>
#include <iostream>
int main() {
std::vector<int> v = {1, 2, 2, 3, 3, 1, 2, 2};
int sum = std::accumulate(v.begin(), v.end(), 0);
std::cout << "Sum: " << sum << std::endl;
return 0;
}
This approach abstracts away the explicit looping logic, making it more readable.
Example in SQL:
SELECT SUM(impressions) FROM db.post;
Here, SQL directly specifies the desired result without defining loops or iteration. The database engine determines the best way to compute the sum efficiently.
Conclusion
Understanding control flow is essential for writing efficient and maintainable programs. Imperative programming provides fine control but requires explicit steps, while declarative programming simplifies code by focusing on results rather than process details.
Read about Exceptional Control Flow