The best analogy I can come up with regarding this is like digging a hole.
When you call a function, you dig a hole into the ground. To get back to where you started, you have to climb out of the hole.
For example,
#include <iostream>
void first() {
std::cout << "Hello. This is the first function." << std::endl;
// We are returning back to where we started (climbing back out of the hole)
return;
}
int main() {
// Dig the hole
first();
std::cout << "Hello. This is the main function." << std::endl;
}
output
Hello. This is the first function.
Hello. This is the main function.
Makes sense? But what happens when there is a second function (we dig even deeper)?
#include <iostream>
// Declarations so that the definitions can be in an order that
// clearer for the purposes of this example.
void first();
void second();
int main() {
std::cout << "Hello. This is the main function." << std::endl;
// Dig the hole
first();
std::cout << "Hello again. We're back in the main function." << std::endl;
}
void first() {
std::cout << "Hello. This is the first function." << std::endl;
// Dig the hole even deeper.
second();
// After climbing out of the hole from the second function,
// we're back in the first.
std::cout << "Hello again. We're back in the first function." << std::endl;
// Now, we climb out of the hole we made by this function
// and return to main().
return;
}
void second() {
std::cout << "Hello. This is the second function." << std::endl;
// Climb back out of the hole and return to the first function
// where we started this hole.
return;
}
output
Hello. This is the main function.
Hello. This is the first function.
Hello. This is the second function.
Hello again. We're back in the first function.
Hello again. We're back in the main function.
Does that help at all?