0
0
C++programming~10 mins

Function calling in C++ - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Function calling
Start main()
Call function foo()
Execute foo() body
Return from foo()
Continue main()
End main()
The program starts in main(), calls a function, executes it, returns, then continues main() until it ends.
Execution Sample
C++
int foo() {
    return 42;
}

int main() {
    int x = foo();
    return 0;
}
Calls function foo() from main(), assigns its return value to x.
Execution Table
StepActionFunctionVariable StateOutput/Return
1Start main()mainx: uninitializednone
2Call foo()main -> foox: uninitializednone
3Execute foo() bodyfoononereturn 42
4Return from foo()foo -> mainx: uninitialized42
5Continue main()mainx: 42none
6End main()mainx: 42program ends
💡 main() ends after calling foo() and assigning its return value to x
Variable Tracker
VariableStartAfter Step 4Final
xuninitializeduninitialized42
Key Moments - 3 Insights
Why does the program jump to foo() when main() calls it?
When main() calls foo() (see Step 2), the program pauses main() and starts executing foo() (Step 3). This is how function calls work: control moves to the called function.
How does the value 42 get assigned to x in main()?
foo() returns 42 at Step 3, then at Step 4 main() receives this value and assigns it to x. The return value passes back to the caller.
What happens after foo() finishes?
After foo() returns (Step 4), control goes back to main() (Step 5) and continues executing the rest of main() until it ends.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of x immediately after Step 4?
A0
B42
Cuninitialized
Dnone
💡 Hint
Check the 'Variable State' column at Step 4 in the execution_table.
At which step does the program start executing the body of foo()?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' and 'Function' columns in the execution_table.
If foo() returned 100 instead of 42, what would be the value of x after Step 4?
A100
B42
Cuninitialized
D0
💡 Hint
Refer to the 'Variable State' column and understand that x gets the return value from foo().
Concept Snapshot
Function calling in C++:
- Use functionName() to call a function.
- Control jumps to the called function.
- The function runs its code and returns a value.
- The caller receives the return value and continues.
- Variables can store returned values.
Full Transcript
This example shows how a function is called in C++. The program starts in main(), then calls foo(). Control moves to foo(), which executes and returns 42. The return value is assigned to variable x in main(). Then main() continues and ends. The execution table traces each step, showing variable states and function transitions. Key moments clarify why control jumps and how return values work. The quiz tests understanding of variable values and execution steps.