Skip to main content

Section 5.2 Flow of Execution

When you look at a program that contains several functions, it is tempting to read it in order from top to bottom. But that is not the flow of execution, or the order the program actually runs.
Programs always begin at the first statement of main, regardless of where it is in the source file. Statements are executed one at a time, in order, until you reach a function invocation, which you can think of as a detour. Instead of going to the next statement, you jump to the first line of the invoked function, execute all the statements there, and then come back and pick up exactly where you left off.
Watching this process play out in Codelens is perhaps the best way to understand what is happening. Don’t worry too much about what this code does (or what void means), pay attention to how the flow of execution works as we encounter function calls:
Listing 5.2.1.
That flow is a little convoluted. In the middle of main, we jump off to printMessageTwice. While in that function, we twice jump off to execute printMessage. Then, once we are back in main, we call invokes printMessage directly, which causes yet another detour.
Fortunately, C++ is good at keeping track of which functions are running. So when printMessage or printMessageTwice completes, it picks up where we left off in the calling function.

Checkpoint 5.2.1.

What order will the letters be printed in the program below? Trace the execution by hand and arrange the blocks in the order the output would be printed.
Start in main. Every time you encounter a function call, remember where you are so you can return there when you are done with the function.
#include <iostream>
using namespace std;

void doThing() {
    cout << "A" << endl;
}

void doOther() {
    cout << "B" << endl;
}

void doIt() {
    cout << "C" << endl;
}

void doThat() {
    cout << "D" << endl;
}

void doMultiple() {
    doThat();
    doOther();
    cout << "E" << endl;
    doIt();
}

int main() {
    cout << "F" << endl;
    doMultiple();
    doThing();
}

Checkpoint 5.2.2.

Manually trace the code. How many calls to hi are made during the execution of the entire program?
Start in main. Every time you encounter a function call, remember where you are so you can return there when you are done with the function.
void hi() {
  cout << "hiii !"<< endl;
}

void printGreeting(){
  hi();
  cout << "how are you doing today. "<< endl;
  hi();
}

int main () {
  hi();
  printGreeting();
  hi();
}
  • 1 call
  • hi( ) is called from multiple functions.
  • 4 calls
  • Correct! main calls hi() twice, and calls printGreeting() once. printGreeting() calls hi() two times.
  • 2 calls
  • hi( ) is called twice from main, but it is also called from printGreeting( ). And printGreeting( ) is called once from main.
  • 3 calls
  • printGreeting() calls hi() two times.
You have attempted of activities on this page.